Sunday, 8 September 2013

template class instance receiving another instance of the same template class of different type

template class instance receiving another instance of the same template
class of different type

How can a template class instance receive another instance of the same
template class of different type as an argument to some of its function
member? (It's hard for me to express my question in simpler way and I'm so
sorry for that.)
Here is a working code. I created a class and I named it MyClass. It
accepts same template class of the same type(which is int) on its
operator= and operator+ member functions.
#include <iostream>
using namespace std;
template<class T>
class MyClass {
protected:
T __val;
public:
MyClass();
MyClass(T val): __val(val) {}
void operator= (const MyClass<T>& r)
{
__val = (T)r.__val;
}
const MyClass<T>& operator+ (const MyClass<T>& r)
{
return *(new MyClass<T>(__val + (T)r.__val));
}
T retval() {return __val;}
};
int main()
{
MyClass<int> myclass1(1);
MyClass<int> myclass2(2);
MyClass<int> myclass3 = myclass1 + myclass2;
cout << myclass3.retval() << endl;
return 0;
}
I typecasted __val members of arguments for operator= and operator+ for
the following purpose:
int main()
{
MyClass<int> myclass1(1);
MyClass<double> myclass2(2.5);
MyClass<int> myclass3 = myclass1 + myclass2;
cout << myclass3.retval() << endl;
return 0;
}
obviously I'll get an error. I cannot pass myclass2 as an argument to
operator+ of myclass1 simply because MyClass<int>::operator+ wants
MyClass<int> argument, and not MyClass<double>. I know that I can overload
another operator+ that accepts MyClass<double>, but I also want to do it
with other number types such as float, single, etc. Making overloaded
functions for all of them makes my code bigger, which I obviously don't
want to happen.
What do I have to change from MyClass to make my second main function work?

No comments:

Post a Comment