如何在不提及结构体类型名称的情况下返回结构体字面值?

huangapple go评论71阅读模式
英文:

C: how to return a struct literal without mentioning its type name?

问题

我们可以通过将匿名文字初始化器强制转换为返回类型来从函数中返回结构体字面量:

struct foo f() {
    return (struct foo) { .bar = 42 };
}

是否可以在初始化器中完全不提及 struct foo 而实现相同效果?单独的声明:

struct foo result = {
    .bar = 42
};
return result;

不可行,因为它仍然显式提及了 struct foo 类型。

是否可以使用 typeof 获取封闭函数的返回类型?我尝试过:

  • return (typeof(#__func__())) { .bar = 42 };
  • return (__auto_type) { .bar = 42 };

但显然 C 的类型推断不会超出单个表达式的范围。

我正在编写一个预处理宏,希望避免为类型提供额外参数。

欢迎提供与 gcc 相关的解决方案。

英文:

We can return struct literal from a function by casting anonymous literal initializer to the return type:

struct foo f() {
    return (struct foo) { .bar = 42 };
}

Is it possible without mentioning struct foo anywhere in the initializer? Separate declaration:

struct foo result = {
    .bar = 42
};
return result;

will not do, as it still explicitly mentions the struct foo type.

Is it possible to get the return type of enclosing function with typeof? I tried:

  • return (typeof(#__func__())) { .bar = 42 };
  • and return (__auto_type) { .bar = 42 };,

but apparently C's type inference doesn't go outside of a single expression.

I'm writing a preprocessor macro and would like to avoid the extra argument for the type.

gcc specific solutions are welcome.

答案1

得分: 1

不可能。复合字面值的声明(6.7.6)和初始化都需要类型说明符(6.5.2.5、6.7.9)。

英文:

No. It is not possible. Both a declaration (6.7.6) and an initialization of compound literals requires a type specifier (6.5.2.5, 6.7.9).

答案2

得分: 0

根据最新的公开C11标准草案在撰写时的规定,“6.5.2.5 复合文字”(结构体初始化器)如下所示:

带括号的类型名称后跟花括号括起的初始化器列表组成的后缀表达式是_复合文字_。

(粗体强调为我的添加)。

事实上,与类型转换无关,除了语法类似。

我相信,这是C标准中指定struct字面值的唯一方式。

英文:

Per the latest public C11 standard draft at the time of writing, "6.5.2.5 Compound literals" (which are struct initializers):
> A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal.

(bold emphasis is mine).

Indeed, it has nothing to do with type cast, except for similar syntax.

I believe, this is the only way in C standard to specify struct literals.

huangapple
  • 本文由 发表于 2023年1月9日 10:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定