Question

I am trying to write a C++ program which wraps numeric values, I am doing this by writing a super class which will handle two simple functions, and an operator overloading function. This is my code:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;


template <class T>
class Number {
protected:
    T number;

public:
    Number(T num) {
        number = num;
    }

    string mytype() {
        return typeid(number).name();
    }

    string what_am_i() {
        ostringstream oss;
        oss << "I am " << Number<T>::mytype() << " and my nanana is " << number;
        return oss.str();
    }

    Number operator+ (Number an) {
        Number brandNew = NULL;
        brandNew.number = number + an.number;
        return brandNew;
    }
};

class MyInt : public Number<int> {
public:
    MyInt() : Number<int>(0){};
    MyInt(int num) : Number(num){
    }


};

In the Main function I would like to do something like:

 void main() {

    MyInt three = 3;
    MyInt two = 2;
    MyInt five = three + two;
    cout << five.what_am_i();

}

My problem is the addition between three and two, the compiler says:

no suitable user-defined conversion from "Number" to "MyInt" exists

I could solve this by implementing the overloading function in MyInt but since i want to support many classes like MyShort and MyFloat I would like to leave it in the Superclass. Is there any solution? Thanks!

Was it helpful?

Solution

The problem is when you inherit from a class templated the same as the current class. The inherited type will not replaced as you might expect. For example, Number<int> will not be replaced with MyInt for inherited operator +.

The return value and entry parameter of operator + is a Number<int>, not a MyInt. The inherited class must be able to construct a MyInt from a Number<int>. Put below line in MyInt class:

MyInt(const Number<int> &x) : Number<int>(x) {}

 

To avoid the extra work, it's better not to inherit from Number, but instead just put a typedef for int:

typedef Number<int> MyInt;

... and then everything else is OK.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top