Reputation: 265
I have a template class, given below :
class Item
{
T Data;
public:
Item():
Data()
{}
void SetData(T nValue)
{
Data = nValue;
}
T GetData() const
{
return Data;
}
void PrintData()
{
cout << Data;
}
};
It is possible to do the following :
Item<int> item1;
Item<int> item2;
item1 = item2;
But when I do the follwing, I get compile time error:
Item<int> item1;
Item<float> item2;
item1 = item2;
Clearly, compiler does not allow to it because item1
is of int type but item2 is of float type.
How can I achieve the second part?
Upvotes: 2
Views: 74
Reputation: 20738
To do this, you need a templated assignment operator, like this:
template <typename T>
class Item {
/* more */
public:
template <typename U>
Item &operator=(const Item<U> &ref)
{
Data = ref.Data;
return *this;
};
/* more */
};
In addition to that, you might need or want a templated copy constructor:
template <typename U>
Item(const Item<U> &ref):
Data(ref.Data)
{
};
This allows for:
Item<int> foo;
Item<float> bar(foo);
Upvotes: 2