模板函数重载解决方案
Template function overload resolution
考虑以下代码:
#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
是左值。
func(n);
需要转换,两个func
都是可行的,重载是不明确的。
tpl_func(n);
具有完全匹配(template<typename T> void tpl_func(T&)
)。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的固定时间步长与增量时间和插值的解决方案是错误的吗?
- 无法在问题解决方案中执行输出逻辑
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 模板重载解决方案:当多个模板匹配时会发生什么?
- 模板和unique_ptr继承情况下的重载解决方案
- 视觉工作室中涉及 void*、字符串和常量字符 [] 的意外重载解决方案
- C++构建一个带有运算符重载的双边树-什么是好的内存解决方案
- 模板函数重载解决方案
- 重载 C++ 中的输入流我的解决方案中出了什么问题
- c++中按引用传递和按值传递之间重载歧义的实用解决方案