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

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;
    ...
}


我还有一个朋友运算子+添加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)
{
    //...
}


请注意,返回类型应在编译时固定。

关于c++ - 具有不同模板参数作为输入的模板类的好友函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52561233/

10-11 22:20
查看更多