具有不同模板参数作为输入的模板 class 的友元函数

friend function of a template class that has different template parameters as input

我有 class 浮点格式,其中尾数和指数的大小可以指定为模板参数:

template <int _m_size, int _exp_size>
class fpxx {

public:
    const int exp_size      = _exp_size;
    const int m_size        = _m_size;

    bool        sign;
    unsigned    exp;
    unsigned    m;
    ...
}

我还有一个朋友operator+加2个这样的号码:

friend fpxx<_m_size, _exp_size>  operator+(const fpxx<_m_size, _exp_size> left, const fpxx<_m_size, _exp_size> right) 
{
    ...
}

这很好用。

它允许我做这样的事情:

fpxx<18,5> a, b, r;
r = a + b;

但是,我还可以创建一个 operator+ 朋友,它可以添加具有不同尾数和指数大小的数字。 像这样:

fpxx<10,4> a;
fpxx<12,4> a;
fpxx<18,5> r;
r = a + b;

但我不知道如何为此声明函数。

这可能吗?

谢谢! 汤姆

制作您的运算符模板并制作它 friend,类似于:

template <int _m_size, int _exp_size>
class fpxx {

public:
    const int exp_size      = _exp_size;
    const int m_size        = _m_size;

    bool        sign;
    unsigned    exp;
    unsigned    m;

template <int s1, int e1, int s2, int e2>
friend fpxx</*..*/> operator+(const fpxx<s1, e1>& left, const fpxx<s2, e2>& right);

};

template <int s1, int e1, int s2, int e2>
fpxx</*..*/> operator+(const fpxx<s1, e1>& left, const fpxx<s2, e2>& right)
{
    //...
}

注意 return 类型应该在编译时固定。