I am wondering if the following is possible.
Lets say I have a code like this:
template <class NumberType>
struct Number
{
NumberType value;
void operator = (Number in_val)
{
value = in_val;
}
}
So then I would be able to do something like:
Number<int> n1, n2;
n2.value = 5;
n1 = n2;
cout << "Value: " << n1.value << endl;
But this won’t allow me to do the following:
Number<int> n1;
Number<double> n2;
n2.value = 5;
n1 = n2;
cout << "Value: " << n1.value << endl;
How to make this possible?
Do I have to wrap this struct/class with another OR do I have to make some fancy recursion?
p.s.
I have used C++ for some time now but never tried templates. So consider that I’m very new to templates.
— EDIT —
Ok I got it correctly now. But another related question came.
template<class OtherNumType>
Number& operator *= ( const OtherNumType& in_value)
{
value *= in_value;
return *this;
}
This gives a compilation error. Why? What is the correct way?
When the template definition of
Number<T>is considered by the compiler for any specific typeT, the nameNumber(when used as a type name) is interpreted asNumber<T>, whateverTmay be at that point.Hence, for
Number<int>, your current template definition provides only for the assignment operator below:because
Numberis interpreted asNumber<int>at that point.In order to make the operator more flexible, you can turn it into a member template (a templated function in an already templated class):
Note how I have modified the operator not only to accept
Number<T2>for any typeT2, but also make it return*thisand accept the argument as const reference – that is the most common and useful way to define the assignment operator.