gpt4 book ai didi

c++ - 在基于模板的类中重载赋值运算符

转载 作者:行者123 更新时间:2023-11-28 06:13:11 25 4
gpt4 key购买 nike

我正在编写一个库来支持一种整数类型,它有两个模板参数 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;

请告诉我哪里出错了。

最佳答案

假设您正在使用普通类,而不是模板。你有一个类 SomeType并且您想为此类分配一个赋值运算符,以便您可以分配类型为 OtherType 的对象到这个类的对象。所以像这样:

SomeType obj1;
OtherType obj2;
obj1 = obj;

为此,您需要为 SomeType 编写赋值运算符像这样:

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

return *this;
}

将其转换为模板,SomeTypeOtherType是相同模板类的实例化,但具有不同的模板参数。在这种情况下 SomeType变成 fp_int<INT_BITS, FRAC_BITS>OtherType变成类似 fp_int<DIFFERENT_INT_BITS, DIFFERENT_FRAC_BITS> 的东西.

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

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
}

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

关于c++ - 在基于模板的类中重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com