如何在方法模板中使用模板类型的按引用传递参数?
我目前正在努力获取以下代码进行编译.首先,头文件包含带有方法模板的类:
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.