如何在方法模板中使用模板类型的引用传递参数?
我目前正在努力编译以下代码。首先是包含带有方法模板的类的头文件:
// ConfigurationContext.h
class ConfigurationContext
{
public:
template<typename T> T getValue(const std::string& name, T& default) const
{
...
}
}
在其他地方我想像这样调用此方法:
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)'
我检查了明显的错误,例如缺少包含之类的内容。但一切似乎都是对的。我尝试删除模板类型参数的引用传递,如下所示:
template<typename T> T getValue(const std::string& name, T default) const ...
然后它编译时没有任何错误并且运行良好,但我仍然想在此处传递引用...
有人知道这里发生了什么吗?如何进行这项工作?
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);
There I get the following error:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
5
是一个文字,您不能将文字绑定到非const
引用。每个副本或每个const
引用都采用T
:(顺便说一句,我怀疑您的编译器是否接受
T default
,因为default 是一个关键字,不能用作标识符。)
您不能这样做的原因是因为每个非
const
引用获取参数通常意味着被调用者可能会更改值,并且此类更改应该反映在呼叫者的身上。 (参见如何将对象传递给C++中的函数?< /a>) 但是,您无法更改文字或临时值。因此,您不允许将它们传递给非 const 引用。5
is a literal, and you cannot bind literals to non-const
references. Either takeT
per copy or perconst
reference:(BTW, I doubt that your compiler accepts
T default
, becausedefault
is a keyword and must not be used as an identifier.)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.