2

我正在尝试使用类型特征来添加对模板参数的引用。

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< type > 或 S< type& > 是否被实例化。

4

1 回答 1

7

你忘了typedef。只是说你将typename使用一个在模板声明时还不被称为类型的类型名。如果你真的想创建一个 typedef,你实际上还需要那个关键字。而且我认为您在下面使用它时忘记了实际命名类型:

template < class T >
struct S {
  typedef typename add_reference< T >::type reference;
};
...
typedef Bar< Foo > type;
S< type >::reference s = some_foo; // initialize!

请记住初始化引用。如果您事先知道T它永远不是引用(以避免引用到引用的问题),您也可以直接执行此操作:

template < class T >
struct S {
  typedef T &reference;
};

typedef Bar< Foo > type;
S< type >::reference s = some_bar_foo; // initialize!

如果您想做的是创建引用数据成员,那么您的语法没有typedef正确

template < class T >
struct S {
  typename add_reference< T >::type reference;
};
...
typedef Bar< Foo > type;
S< type > s = { some_bar_foo }; // initialize!
s.reference = some_other_bar_foo; // assign "some_other_bar_foo" to "some_bar_foo"

我不知道你到底想做什么。

于 2010-01-10T20:44:19.920 回答