typedef 具有所有默认参数的模板
我声明一个模板类,其中所有参数都具有默认参数,例如:
template<typename TYPE = int>
class Foo {};
那么以下两个是等效的:
Foo<int> one;
Foo<> two;
但是,我不允许这样做:
Foo three;
是否可以使用 typedef
来实现这一点名称相同但没有括号,如下所示:
typedef Foo<> Foo;
I declare a templated class with all parameters having default arguments, for example:
template<typename TYPE = int>
class Foo {};
Then the following two are equivalent:
Foo<int> one;
Foo<> two;
However, I'm not allowed to just do:
Foo three;
Is it possible to achieve that with a typedef
to the same name but without the brackets, like this:
typedef Foo<> Foo;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我做了如下的事情,不知道你是否喜欢:
I do something like the following, I don't know if you will like it or not:
你不能用不同的类型重新声明一个符号,所以无论你能做什么都不会像你期望的那样工作。
如果您想实现此目的,请使用不同的名称作为别名:
You can't redeclare a symbol with a different type, so whatever you will be able to do won't work as you expect.
If you want to achieve this, use a different name as alias :
如果声明
typedef Foo<> Foo;
是允许的,其后是名称无法将
Foo
指定为模板。即,以下内容无效。
虽然上面的
typedef
在实践中是不允许的,如果您仍然需要将
Foo
编写为Foo<>
,如下所示的宏就会达到目的。
If the declaration
typedef Foo<> Foo;
is allowed, thereafter the nameFoo
as a template cannot be specified.That is, the following becomes invalid.
Though the above
typedef
isn't allowed in practice,if you still need to write
Foo
asFoo<>
, a macro like the followingwill meet the purpose.
给出:
该错误几乎说明了问题所在。编译器将
Foo
视为被重新声明。但是,这应该编译并工作:
Gives:
The error pretty much tells what the problem is. Compiler sees
Foo
as being re-declared.However, this shall compile and work:
不可以。尽管您可以为
class
声明与class
同名的typedef
,因为您可以使用 typedef 重新定义名称引用它已经引用的类型。或者如果
A
已声明为类:您不能使用模板的名称来执行此操作(模板的名称不是类的名称),您必须给它一个不同的名称。
No. Although you can declare a
typedef
for aclass
with the same name as aclass
because you can use a typedef to redefine a name to refer to the type to which it already refers.or if
A
was already declared as a class:You can't do that with the name of a template (the name of a template isn't a name of a class), you'd have to give it a different name.
不幸的是,不能,因为
Foo
已经是类模板本身的名称,因此不能是同一命名空间中的任何其他名称。Unfortunately, no, because
Foo
is already the name for the class template itself, and thus can't be anything else in the same namespace.