Using templates with anonymous classes scoped inside a function

坚强是说给别人听的谎言 提交于 2019-12-10 15:52:43

问题


Let's say I have the following snippet:

template <class T> void f(T arg) { arg(); }

void g()
{
   struct { void operator()(void) { } } foo;

   f(foo);
}

Visual C++ accepts this. However, when I try GCC, I get:

$ g++ --version # just in case this matters
g++ (Debian 4.4.5-8) 4.4.5
...
$ g++ foo.cc
foo.cc: In function 'void g()':
foo.cc:7: error: no matching function for call to 'f(g()::<anonymous struct>&)'

When foo is scoped globally and its type has a name, this works. But when the type is anonymous or declared inside g() it does not.

Why does GCC reject this? Is it valid C++?


回答1:


14.3.1 paragraph 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 templateargument for a template typeparameter.

In other words, not valid. Although it would be handy imo, that's maybe why VC allows it.




回答2:


As already said, a local class (a class defined within a function) can not be used as a template argument. Fortunately, C++0x fixes that with lambda functions: http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions



来源:https://stackoverflow.com/questions/4659157/using-templates-with-anonymous-classes-scoped-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!