使用具有作用域在函数内部的匿名类的模板
假设我有以下代码片段:
template <class T> void f(T arg) { arg(); }
void g()
{
struct { void operator()(void) { } } foo;
f(foo);
}
Visual C++ 接受此代码。但是,当我尝试 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>&)'
当 foo 的作用域为全局且其类型有名称时,此方法有效。但是,当类型是在 g()
内声明的匿名类型时,则不会。
为什么海湾合作委员会拒绝这样做?它是有效的 C++ 吗?
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++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
14.3.1 第 2 段:
本地类型、无链接的类型、未命名类型或类型
由任何这些类型组成的化合物不得用作
模板类型参数的 templateargument。
换句话说,无效。虽然这在我看来很方便,但这也许就是 VC 允许它的原因。
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.
正如已经说过的,本地类(在函数中定义的类)不能用作模板参数。幸运的是,C++0x 使用 lambda 函数修复了这个问题:http://en.wikipedia .org/wiki/C%2B%2B0x#Lambda_functions_and_expressions
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