开发者

No matching function call to <anonymous enum>

开发者 https://www.devze.com 2023-02-27 06:42 出处:网络
Given: template<typename T> void f( T ) { } enum {// if changed to \"enum E\" it compiles e }; int main() {

Given:

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

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

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

I get:

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

Yet if the enum declaration is given a name, it compiles. Why doesn't it work for an anonymous enum? Ideally, I'd like it to promote the enum value e to an int an开发者_运维百科d instantiate f(int).


Unnamed type simply cannot be used as a template argument

C++03 says in 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.

This limitation was lifted in C++0x, and your program compiles with no diagnostics with MSVC++ 2010 and gcc 4.5.2 in C++0x mode.


Ideally, I'd like it to promote the enum value e to an int and instantiate f(int).

f(+e);


You can always explicitly do the promotion to clearly show your intention:

f(static_cast<int>(e));

0

精彩评论

暂无评论...
验证码 换一张
取 消