考虑这段代码:
#include <iostream>
void func(int&)
{
std::cout << "mutable" << std::endl;
}
void func(const int&)
{
std::cout << "const" << std::endl;
}
template<typename T>
void tpl_func(T&)
{
std::cout << "mutable_tpl" << std::endl;
}
template<typename T>
void tpl_func(const T&)
{
std::cout << "const_tpl" << std::endl;
}
class number
{
public:
operator int&()
{
return nb_;
}
operator const int&()
{
return nb_;
}
private:
int nb_ = 42;
};
int main()
{
number n;
func(n); // This produces: error: call to 'func' is ambiguous
tpl_func(n); // This compiles fine
}
使用 clang3.5 测试
问题:
- 为什么模板函数的重载决议没有歧义?
- 什么规则决定选择哪个重载?
最佳答案
因为在 func(n)
有一个隐式函数调用(int 转换运算符)是不明确的(您可以选择两者中的任何一个)并且在 tpl_func(n)
中你不是 int 转换,即模板推导为 tpl_func<number>(number &)
自 n
是左值。
关于c++ - 模板函数重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26512477/