boost add_reference 不适用于模板参数
我正在尝试使用类型特征来添加对模板参数的引用。
template < class T >
struct S {
typename add_reference< T >::type reference; // reference member should always be a reference
};
...
typedef Bar< Foo > type;
S< type > s; // does not add reference, S:: reference is of type type, not type&
然而它似乎不起作用。这是正确的做法吗?我的编译器是 g++ 4.3。 谢谢。
澄清:我希望参考成员可以作为参考,无论 S< 是否为参考成员。类型>或S<类型& >被实例化。
I am trying to use type traits to add reference to a template parameter.
template < class T >
struct S {
typename add_reference< T >::type reference; // reference member should always be a reference
};
...
typedef Bar< Foo > type;
S< type > s; // does not add reference, S:: reference is of type type, not type&
However it does not seem to work. is it the right way to do it? my compiler is g++ 4.3.
thanks.
clarification: I have would like reference member to be reference, regardless if S< type > or S< type& > is instantiated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忘记了
typedef
。typename
只是表示您将使用在模板声明时尚未被称为类型的类型名称。如果您确实想创建 typedef,则实际上还需要该关键字。我认为您在下面使用它时忘记了实际命名类型:记住初始化引用。如果您事先知道
T
永远不是引用(以避免引用到引用问题),您也可以直接执行此操作:如果您想要做的是创建一个引用数据成员,没有
typedef
的语法是正确的,我不知道你到底想做什么。
You forgot
typedef
. Thetypename
just says that you are going to use a typename that at the point of the template declaration is not yet known as a type. If you actually want to create a typedef, you actually need that keyword in addition. And i think you forgot to actually name the type when you use it below:Remember to initialize the reference. If you know in advance that
T
is never a reference (to avoid the reference-to-reference problem) you can also do this directly:If what you wanted to do is to create a reference data member, your syntax without
typedef
was correctI do not know what you want to do exactly.