我有这个测试源:
#include <stdio.h>
int main()
{
int x;
printf("x=%d\n", _Generic('x', int: 1, default: 0));
return 0;
}
使用 c++(来自 GCC 4.9.2)编译失败:
t.cpp: In function ‘int main()’:
t.cpp:7:33: error: expected primary-expression before ‘int’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:41: error: expected primary-expression before ‘default’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:51: error: ‘_Generic’ was not declared in this scope
printf("x=%d\n", _Generic('x', int: 1, default: 0));
编译器参数是:
c++ --std=c++11 t.cpp -o t
我做错了什么?
最佳答案
_Generic
是一个 C11 特性。它不存在于 C++ 中(任何至少达到 C++14 的版本——我也不希望它被添加)。
如果你想使用它,你需要编写 C 代码,并使用支持该标准的编译器(例如,gcc 和 clang 的合理最新版本,使用 -std=c11
).
如果您想编写 C++,请改用重载或模板,例如:
#include <iostream>
int foo(int) { return 1; }
int foo(char) { return 0; }
int main()
{
std::cout << "x=" << foo('x') << std::endl;
}
这在 C++ 中打印 x=0
,foo(char)
重载是最佳匹配。
请注意,C 和 C++ 之间的区别也可能在这里欺骗您:'x'
在 C++ 中是一个字符。它是 C 中的 int
。因此,如果 _Generic
已由您的编译器实现(可能作为扩展),那么在将您的示例编译为 C 时,您可能会得到不同的输出与编译为 C++。
关于c++11 - 如何启用 _Generic 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28253867/