2016-02-28 95 views
0

是否可以为不同的模板参数定义不同的=运算符。让我们假设我想用不同的方法来转换不同类型的参数:如何根据类参数定义成员类运算符

template <class T,class U> 
class cTest 
{ 
    private: 
    public: 
    T x; 
    U y; 

    //typical case 
    cTest<T,U>& operator =(const cTest<T,U> &that) 
    { 
    return *this; 
    } 

    //operator = based on the LHS type 1 
    cTest<uint16_t,U>& operator =(const cTest<int,U> &that) 
    { 
    cout<<"cTest<uint16_t,U>& operator =(const cTest<int,U> &that)"<<endl; 
    return cTest<uint16_t,U>(); 
    } 
    //operator = based on the LHS type 2 
    cTest<uint8_t,U>& operator =(const cTest<int,U> &that) 
    { 
     cout<<"cTest<uint8_t,U>& operator =(const cTest<int,U> &that)"<<endl; 
     return cTest<uint16_t,U>(); 
    } 
}; 

回答

2

您试图返回类型重载运算符/功能。这不是由C++标准允许的:

13.1/2:某些函数声明不能​​被重载: - 仅在不同的返回类型不能 重载函数声明。

可能的解决方法:

  • 你可以考虑使用的功能上,而不是运营商,通过引用传递变量存储返回值。在这种情况下,过载是可能的。但它比赋值运算符不太方便,我想这不是你想要的。
  • 更好的方法是在cTest<uint16_t,U>cTest<uint8_t,U>之间添加一个单独的转换运算符。
1

我建议你看看Template Metaprogramming

模板元编程是一种通用编程技术,它使用极其早期的绑定。编译器作为解释器或“虚拟计算机”发出构成最终程序的指令。它可以用于静态配置,自适应程序,优化等等。

你基本上可以让编译器决定使用哪个模板定义,具体取决于各自的值。四元数乘法的例子如下所示:

template <typename Quaternion> 
typename std::enable_if_t<sds::is_quaternion<Quaternion>::value, Quaternion> 
operator+(const Quaternion &a, const Quaternion &b) 
{ 
    return Quaternion 
     (
      a.u() + b.u(), 
      a.v() + b.v() 
     ); 
} 
相关问题