gpt4 book ai didi

c++ - boost add_reference 不适用于模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:05:35 26 4
gpt4 key购买 nike

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

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

最佳答案

您忘记了 typedeftypename 只是表示您将要使用一个在模板声明处尚未被称为类型的类型名。如果你真的想创建一个 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"

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

关于c++ - boost add_reference 不适用于模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com