c++ - 没有对 <anonymous enum> 的匹配函数调用

标签 c++ templates enums

给定:

template<typename T>
void f( T ) {
}

enum {    // if changed to "enum E" it compiles
  e
};

int main() {
  f( e ); // line 10
}

我得到:

foo.cpp: In function ‘int main()’:
foo.cpp:10: error: no matching function for call to ‘f(<anonymous enum>)’

然而,如果为 enum 声明命名,它就会编译。为什么它不适用于匿名枚举?理想情况下,我希望它将枚举值 e 提升为 int 并实例化 f(int)

最佳答案

未命名类型根本不能用作模板参数

C++03 在 14.3.1[temp.arg.type]/2

中说

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

此限制在 C++0x 中解除,您的程序在 C++0x 模式下使用 MSVC++ 2010 和 gcc 4.5.2 进行编译时没有诊断。

关于c++ - 没有对 <anonymous enum> 的匹配函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5720359/

相关文章:

c++ - 什么时候应该使用 std::thread::joinable?

C++需要从数组中找到符号

c++ - 如何解决 MSVC 2012 中的 `using K = ...`?

c++ - std::enable_if 的两个版本有什么区别

c++ - 是否使用非虚析构函数和基类指针释放了整个对象?

c++ - C++ 上的预处理器重载

c - C 中模板的模拟(对于队列数据类型)

c++ - “enum class”的递增和递减

java - 使用 setter 将服务注入(inject)枚举......不好的做法?

c++ - 如何在 C++ 中创建原子枚举?