0

I have class for floating point format where the size of the mantissa and the exponent can be specified as a template parameter:

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

I also have a friend operator+ to add 2 such numbers:

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

This works fine.

It allows me to do things like this:

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

However, I would also be able create an operator+ friend that makes it possible to add numbers with different mantissa and exponent sizes. Like this:

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

But I have no idea how to do declare the function for that.

Is this possible?

Thanks! Tom

Tom Verbeure
  • 232
  • 2
  • 8
  • Make it its own template. Also, something isn't matching here. `fpxx` takes 2 non type parameters but you define your friend function using 3. – NathanOliver Sep 28 '18 at 19:00
  • I've edited my example. I had simplified it before submitting, but I hadn't simplified it everywhere. – Tom Verbeure Sep 28 '18 at 20:26

1 Answers1

2

Make your operator template and make it friend, something like:

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)
{
    //...
}

Notice that return type should be fixed at compile time.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thanks! That's getting me a whole lot further. However, after adding this, I now get an "ambiguous overload for ‘operator+’" error and "note: candidate: operator+(float, float) ". I think this is because I also a " operator float () const " operator. How do I make it know that it should use the + operator instead of the type conversion operator? – Tom Verbeure Sep 28 '18 at 21:37
  • Create a new Question. – Jarod42 Sep 28 '18 at 21:55