Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top