【问题标题】:Overloading Assignment operator in template based class在基于模板的类中重载赋值运算符
【发布时间】:2015-06-15 08:13:43
【问题描述】:

我正在编写一个库来支持具有两个模板参数INT_BITSFRAC_BITS 的整数类型。我成功地编写了一个转换函数来将不同的类类型从一种转换为另一种[INT_BITSFRAC_BITS 的值不同]。但是当我尝试在赋值运算符的重载中使用它时它不起作用。请建议我一种实现它的方法。我浏览了链接 here herehere ,但似乎没有一个解决方案有效。

类定义:

template<int INT_BITS, int FRAC_BITS>
struct fp_int
{
public:
    static const int BIT_LENGTH = INT_BITS + FRAC_BITS; 
    static const int FRAC_BITS_LENGTH = FRAC_BITS;

private:
    ValueType stored_val;
};

转换函数定义:

template <int INT_BITS_NEW, int FRAC_BITS_NEW>
fp_int<INT_BITS_NEW, FRAC_BITS_NEW> convert() const
{
    typedef typename fp_int<INT_BITS_NEW, FRAC_BITS_NEW>::ValueType TargetValueType;

    return fp_int<INT_BITS_NEW, FRAC_BITS_NEW>::createRaw(
        CONVERT_FIXED_POINT<
            ValueType,
            TargetValueType,
            (FRAC_BITS_NEW - FRAC_BITS),
            (FRAC_BITS_NEW > FRAC_BITS)
            >:: exec(stored_val));
}

运算符定义如下:

template <int INT_BITS_NEW, int FRAC_BITS_NEW>
fp_int<INT_BITS_NEW, FRAC_BITS_NEW>
    operator =(fp_int<INT_BITS,FRAC_BITS> value) const
{
     fp_int<INT_BITS_NEW,FRAC_BITS_NEW> a = value.convert<INT_BITS_NEW,FRAC_BITS_NEW>();
     return a;
}

当我尝试这个时,它会起作用:

fp_int<8,8> a = 12.4;
fp_int<4,4> b = a.convert<4,4>();

但是当我尝试这样做时,它会显示类型转换错误:

fp_int<8,8> a = 12.4;
fp_int<4,4> b;
b = a;

请告诉我哪里出错了。

【问题讨论】:

  • 赋值运算符通常应该通过引用获取他们的参数。此外,您没有在赋值运算符中 assigning,也就是说,您没有修改左操作数。这很令人惊讶:它不遵循内置赋值的行为。
  • 请提供MCVE
  • @m.s.请在repo_link找到文件

标签: c++ templates type-conversion operator-overloading template-meta-programming


【解决方案1】:

假设您使用的是普通类,而不是模板。你有一个SomeType 类,并且你希望这个类有一个赋值运算符,这样你就可以将OtherType 类型的对象分配给这个类的对象。所以是这样的:

SomeType obj1;
OtherType obj2;
obj1 = obj;

为此,您可以为SomeType 编写赋值运算符,如下所示:

SomeType& operator=(const OtherType& other)
{
    // implementation...

    return *this;
}

将其转换为模板,SomeTypeOtherType 是相同模板类的实例化,但具有不同的模板参数。 在这种情况下,SomeType 变为 fp_int&lt;INT_BITS, FRAC_BITS&gt;OtherType 变为 fp_int&lt;DIFFERENT_INT_BITS, DIFFERENT_FRAC_BITS&gt;

所以你的操作符应该是这样的:

template <int DIFFERENT_INT_BITS, int DIFFERENT_FRAC_BITS>
fp_int<INT_BITS, FRAC_BITS>&
    operator =(fp_int<DIFFERENT_INT_BITS, DIFFERENT_FRAC_BITS> value)
{
    // proper implementation for an assignment operator
}

将上面的模板参数与您的示例中的参数进行比较以查看差异。基本上,您试图以错误的方向进行转换,这就是您收到有关类型转换的编译错误的原因。

【讨论】:

  • - 非常感谢,我终于想出了一个实现并理解我的错误。
猜你喜欢
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多