如何在方法模板中使用模板类型的按引用传递参数? [英] How to use pass-by-reference arguments of template type in method templates?

查看:304
本文介绍了如何在方法模板中使用模板类型的按引用传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力获取以下代码进行编译.首先,头文件包含带有方法模板的类:

I am currently struggling to get the following code to compile. First the header file containing a class with a method template:

// ConfigurationContext.h

class ConfigurationContext
{
    public:
    template<typename T> T getValue(const std::string& name, T& default) const
        {
            ...
        }
}

我想在其他地方这样调用此方法:

Somewhere else I want to call this method like this:

int value = context.getValue<int>("foo", 5);

出现以下错误:

error: no matching function for call to 'ConfigurationContext::getValue(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, int)'

我检查了明显的错误,例如缺少包含和类似的东西.但是一切似乎都是正确的.我试图删除模板类型参数的传递引用,如下所示:

I checked the obvious errors like missing includes and stuff like that. But everything seems to be right. I tried removing the pass-by-reference of the template type argument like this:

template<typename T> T getValue(const std::string& name, T default) const ...

然后它可以编译而没有任何错误,并且可以正常运行,但是我仍然想在这里传递引用...

Then it compiles without any errors and also runs fine, but I'd still like to pass in a reference here...

有人知道这里发生了什么以及如何使它工作吗?

Does anybody know whats happening here and how to make this work?

推荐答案

5是文字,并且不能将文字绑定到非const引用.每个副本或每个const参考均采用T:

5 is a literal, and you cannot bind literals to non-const references. Either take T per copy or per const reference:

template<typename T> T getValue(const std::string& name, const T& def) const

(顺便说一句,我怀疑您的编译器接受T default,因为default是关键字,不能用作标识符.)

(BTW, I doubt that your compiler accepts T default, because default is a keyword and must not be used as an identifier.)

之所以不能执行此操作,是因为每个非const引用都接受参数通常意味着被调用方可能会更改值,并且此类更改应反映在调用方的位置. (请参阅如何将对象传递给C ++中的函数?)但是,您不能更改文字或临时字符.因此,您不允许将它们传递给非const引用.

The reason you cannot do this is because taking arguments per non-const reference usually implies that the callee might change the value and such changes should reflect at the caller's. (See How to pass objects to functions in C++?) However, you cannot change literals or temporaries. So you are not allowed to pass them to non-const references.

这篇关于如何在方法模板中使用模板类型的按引用传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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