c++ - 定义模板化运算符重载时出错

标签 c++ templates c++11 operator-overloading

这是 operator+ 的尝试模板化重载。这无法同时使用 gcc 4.8 和 icc 14.0.3 进行编译。

template <typename T>
class B
{
public:
  B operator+(const B& rhs)
  {
    return *this;
  }
};

template <typename T>
class A
{
public:
  operator B<T>() const{return B<T>();}
};

// template<typename T>                                                                                                                                                        
// B<T> operator+(A<T> const& t, A<T> const& u)                                                                                                                                
// {                                                                                                                                                                           
//   return (B<T>)t + (B<T>)u;                                                                                                                                                 
// }                                                                                                                                                                           

template<typename T, typename U>
B<U> operator+(A<T> const& t, A<T> const& u)
{
  return (B<U>)t + (B<U>)u;
}

int main()
{
  A<double> a,b;
  B<double> c = a+b;
  return 0;
}

但是,注释的重载工作正常。有什么不同?为什么带有两个参数的模板不匹配?

g++48 -std=c++11 temp2.cpp
temp2.cpp: In function ‘int main()’:
temp2.cpp:33:18: error: no match for ‘operator+’ (operand types are ‘A<double>’ and ‘A<double>’)
   B<double> c = a+b;
                  ^
temp2.cpp:33:18: note: candidate is:
temp2.cpp:25:6: note: template<class T, class U> B<U> operator+(const A<T>&, const A<T>&)
 B<U> operator+(A<T> const& t, A<T> const& u)
      ^
temp2.cpp:25:6: note:   template argument deduction/substitution failed:
temp2.cpp:33:19: note:   couldn't deduce template parameter ‘U’
   B<double> c = a+b;

最佳答案

编译器告诉你失败的原因:

temp2.cpp:25:6: note: template argument deduction/substitution failed:
temp2.cpp:33:19: note: couldn't deduce template parameter ‘U’

模板参数U只出现在函数模板的返回类型中,因此无法推导。如果您显式列出模板参数,您的代码将编译

B<double> c = operator+<double, double>(a, b);

如果您交换模板参数的顺序,使 U 出现在 T 之前,您仍然可以推导 T

template<typename U, typename T>
B<U> operator+(A<T> const& t, A<T> const& u)
{
  return (B<U>)t + (B<U>)u;
}

B<double> c = operator+<double>(a, b);

注释掉的 operator+ 实现有效,因为返回类型也使用相同类型的参数 T,因此可以从函数模板参数中推导出它。

关于c++ - 定义模板化运算符重载时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24194765/

相关文章:

c++ - 返回 bool 值的递归函数?

c++ - “GetConsoleWindow”未在此范围内声明?

c++ - 是作者炫耀还是真实的做法

c# - 是否可以在C#中创建 “perfect forwarding”泛型集合?

c++ - 按值返回到右值引用

c++ - 有什么比元工厂更好的解决构造函数注入(inject)到 CRTP 中的派生类的问题吗?

c++ - 如何在 OpenMP C++ 中分配动态内存

c++ - 遍历数组最有效的方法是什么? (c++)

c++ - 模板内的参数相关查找

c++ - `decay_copy` 对象的构造函数中的 `std::thread` 有何作用?