Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Problem: Class Promotion using derived class

I have a class for Float32 that is derived from Float32_base


    class Float32_base {
        public:
        // Constructors
        Float32_base(float x) : value(x) {};
        Float32_base(void) : value(0) {};
        operator float32(void) {return value;};
        Float32_base operator =(float x) {value = x; return *this;};
        Float32_base operator +(float x) const { return value + x;};

    protected:
        float value;

    }

    class Float32 : public Float32_base {
        public:
        float Tad() {
            return value + .01;
        }
    }

    int main() {
        Float32 x, y, z;
        x = 1; y = 2;

    // WILL NOT COMPILE!
        z = (x + y).Tad(); 

    // COMPILES OK
        z = ((Float32)(x + y)).Tad(); 
    }

The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's.

Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

like image 896
Michael Fitzpatrick Avatar asked May 22 '26 21:05

Michael Fitzpatrick


1 Answers

You can use CRTP if you only need one-level deep inheritance:

template <typename T>
struct A
{
  T
  operator+ (const A&)
  { return T (); }
};

struct B : A <B>
{
  void
  lol ()
  { }
};

int
main ()
{
  B a, b;
  (a + b).lol ();
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!