首页 > 解决方案 > 具有不同模板参数作为输入的模板类的友元函数

问题描述

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

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;

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

这可能吗?

谢谢!汤姆

标签: c++templatesfriend

解决方案


制作您的运营商模板并制作它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)
{
    //...
}

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


推荐阅读