模板函数重载解决方案

Template function overload resolution

本文关键字:解决方案 重载 函数      更新时间:2023-10-16

考虑以下代码:

#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&))。