我目前正在努力编译以下代码。首先是包含带有方法模板的类的头文件:
// 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 ...
然后它编译没有任何错误并且运行良好,但我仍然想在这里传递一个引用...
有没有人知道这里发生了什么以及如何让它工作?
最佳答案
5
是文字,您不能将文字绑定(bind)到非 const
引用。每个拷贝或每个 const
引用获取 T
:
template<typename T> T getValue(const std::string& name, const T& def) const
(顺便说一句,我怀疑你的编译器是否接受 T default
,因为 default
是一个关键字,不能用作标识符。)
你不能这样做的原因是因为每个非 const
引用的参数通常意味着被调用者可能会改变值,而这种改变应该反射(reflect)在调用者的身上。 (参见 How to pass objects to functions in C++?)但是,您不能更改文字或临时值。所以不允许将它们传递给非 const
引用。
关于c++ - 如何在方法模板中使用模板类型的引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3508053/