如何根据类参数

时间:2016-02-28 18:29:08

标签: c++ class templates c++11

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

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 个答案:

答案 0 :(得分:2)

您正尝试按返回类型重载运算符/函数。 C ++标准不允许这样做:

  

13.1 / 2:某些函数声明无法重载: - 仅在返回类型上有所不同的函数声明不能   超载。

可能的解决方法:

  • 您可以考虑在运算符上使用函数,通过引用传递一个变量来存储返回值。在这种情况下,过载是可能的。但它不如分配算子那么方便,我想这并不是你想要的。
  • 更好的方法是在cTest<uint16_t,U>cTest<uint8_t,U>之间添加单独的转换运算符。

答案 1 :(得分: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()
        );
}