c++11 - 如何启用 _Generic 关键字

标签 c++11

我有这个测试源:

#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=0foo(char) 重载是最佳匹配。

请注意,C 和 C++ 之间的区别也可能在这里欺骗您:'x' 在 C++ 中是一个字符。它是 C 中的 int。因此,如果 _Generic 已由您的编译器实现(可能作为扩展),那么在将您的示例编译为 C 时,您可能会得到不同的输出与编译为 C++。

关于c++11 - 如何启用 _Generic 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28253867/

相关文章:

c++ - 为什么有些类型不能使用统一的初始化语法?

c++ - 变量的静态初始化失败

c++ - 将临时地址传递给带有指针参数的函数是否合法

c++ - 如何将n个连续元素插入到元素类型不可复制的std::vector中?

c++ - 根据标准,这些编译器中的哪个有错误?

c++ - vector<unique_ptr<myclass>> 元素之间的指针

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?

c++ - C++11 lambdas 如何表示和传递?

c++ - vs2012 rc 中基于范围的 for 循环

c++ - RValue、模板解析和复制构造函数(在 Visual C++ 2010 中)