繁体   English   中英

c ++模板中的const引用

[英]const references in c++ templates

在具有泛型类型T的C ++模板中,我可以使用

const T &

获取对常量T的引用。但是,如果现在T本身是引用类型(例如T = int&),则上述术语解析为

int &

而不是

const int &

这很有意义,因为任何引用本身都是不变的。 但是,还有一种方法需要一个

const T &

如果T本身是参考类型?

编辑:要评估的示例代码(g ++编译器):

template <typename T> class TemplateClass
{
public:
    void foo(const T &bar) { }
};

int main()
{
    TemplateClass<int &> x;
    x.foo(0);   // <-- compile error: no conversion from int to int&
    return 0;
}

删除参考:

template<typename T>
void Test(const typename std::remove_reference<T>::type & param)
{
        param = 20;
}

现在它按预期工作。

您始终可以使用模板专门化为任何类型的引用实现不同的版本:

template <typename T> struct X {
  void foo(T const&);
};

template <typename T> struct X<T&> {
  void foo(T const&);
};

现在, X<int>::foo需要一个int const&X<int&>::foo需要一个int const&

但是,从你的问题中你并不完全清楚你要做什么。


编辑:如果没有模板专业化,我的g ++版本(4.6.1)不会抱怨以下内容

int i = 7;
X<int&>(i);

虽然它确实适用

X<int&>(7);

哪个是正确的IMO,因为您尝试将临时( 7 )转换为可变引用(即使这是对const引用的引用)。


编辑2:如果你想减少重复的代码,那么不要专门化你的原始类,但使用这个:

template <typename T> struct R {
  typedef T& Ref;
  typedef T const& ConstRef;
};

template <typename T> struct R<T&> {
  typedef T& Ref;
  typedef T const& ConstRef;
};

template<typename T> struct X {
  void foo(typename R<T>::ConstRef x);
};

我遇到了同样的问题。 似乎'&'类型转换运算符比'const'限定符绑定更强。 所以当我们有这个代码时:

template<class t>
void fun(const t i)
{
}

fun<int&>();

函数以void(int&)类型结束,而不是预期的void(const int&)

为了解决这个问题,我已经定义了这个模板:

template<class t> struct constify { typedef t type; };
template<class t> struct constify<t&> { typedef const t& type; };

现在将您的函数定义为:

template<class t>
void fun(typename constify<t>::type i)
{
}

fun<int&>();

根据需要,实例化的函数将具有void(const int&)类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM