C ++模板中的const引用 [英] const references in c++ templates

查看:109
本文介绍了C ++模板中的const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通用类型为T的C ++模板中,我可以使用

In a C++ template with the generic type T, I can use

const T &

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

to get a reference to a constant T. However, if now T itself is a reference type (like e.g. T = int &), the above term resolves to

int &

而不要

const int &

这很有意义,因为任何引用本身总是恒定的。但是,还有一种方法可以要求

which quite makes sense, since any reference itself is always constant. However, is there still a way to require a

const T &

如果T本身是引用类型?

if T itself is a reference type?

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

sample code to evaluate (g++ compiler):

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;
}

现在它可以正常工作了。

Now it works as expected.

这篇关于C ++模板中的const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆