在函数内部使用具有匿名类范围的模板 [英] Using templates with anonymous classes scoped inside a function

查看:144
本文介绍了在函数内部使用具有匿名类范围的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码段:

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

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

   f(foo);
}

Visual C ++接受这个。但是,当我尝试GCC,我得到:

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>&)'

$ b b

foo 在全局范围内,并且其类型有一个名称时,这是有效的。但是当类型是 g()中的匿名时,它不会。

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.

为什么GCC拒绝?是否有效的C ++?

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

推荐答案

14.3.1第2段:

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.

换句话说,是无效的。虽然这将是方便的imo,这也许是为什么VC允许它。

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

这篇关于在函数内部使用具有匿名类范围的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆