模板函数重载决议

时间:2014-10-22 16:33:28

标签: c++ templates overloading

考虑以下代码:

#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进行测试

问题:

  • 为什么模板函数的重载分辨率不明确?
  • 什么规则决定选择哪个重载?

2 个答案:

答案 0 :(得分:3)

因为在func(n)中有一个隐含的函数调用(int转换运算符),它是不明确的(你可以选择其中任何一个)而在tpl_func(n)中你不是int转换,即模板推导为tpl_func<number>(number &),因为n是左值。

答案 1 :(得分:1)

func(n);需要转换,func都可行且重载不明确。

tpl_func(n);具有完全匹配(template<typename T> void tpl_func(T&))。

相关问题