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!
User-defined conversions allow you to specify object conversions that are implicitly applied by the compiler, in addition to standard built-in type conversions.
User-defined conversions perform conversions between user-defined types, or between user-defined types and built-in types. You can implement them as Conversion constructors or as Conversion functions.
You can define a member function of a class, called a conversion function, that converts from the type of its class to another specified type. All three statements in function f(Y) use the conversion function Y::operator int() .
An explicit type conversion is user-defined conversion that forces an expression to be of specific type. An implicit type conversion is performed without programmer's intervention. An explicit type conversion is specified explicitly by the programmer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With