[英]Using templates with anonymous classes scoped inside a function
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. Visual C ++接受这个。 However, when I try GCC, I get: 但是,当我尝试GCC时,我得到:
$ 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. 当foo
全局范围并且其类型具有名称时,这是有效的。 But when the type is anonymous or declared inside g()
it does not. 但是当类型是匿名的或在g()
声明时,它不会。
Why does GCC reject this? GCC为什么拒绝这个? Is it valid C++? 它是有效的C ++吗?
14.3.1 paragraph 2: 14.3.1第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. 虽然它会很方便,但这可能是VC允许它的原因。
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 幸运的是,C ++ 0x修复了lambda函数: http : //en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.