Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a template object change its type?

Tags:

c++

templates

I have the following class

template <typename T> class Item {

public:

    T item;
    Item () : item( T() ) {}
    Item (T arg) { this->item = arg;}

    operator T () const {
        return item;
    }

};

Now I want to write an assignment operator that also changes the type of the object. Is that even possible? I have googled it, but nothing relevant came out of this (which, btw, makes me think that maybe I`m a bit out of my mind).

To make this clear, let`s say I have the 2 following objects:

Item <int> intItem = 3;
Item <double> doubleItem = 3.4;

I want to be able to write

intItem = doubleItem;

And, after this, I want the type of intItem to be Item<double>.

If I only wanted a "classic" assignment operator, it would work just fine if, inside my class, I would have something like

Item<int>& operator= (const Item<double> & var) {
    this->item = var.item;
    return *this;
}

The double value would be rounded, but it would work. Oh, and the type of intItem would remain Item<int>

P.S.: I know about unions and tagged unions, I don't want to use that. My Item class should behave "something like" tagged unions.

So please give me an answer, or tell me I`m dreaming.

like image 300
Hame Avatar asked Jan 11 '23 20:01

Hame


1 Answers

No you can't change the type during runtime, as templates are a compile-time thing.

In fact, it would be like having a variable declared as int and try to change it to a float. Yes you can assign the variable to another float variable, but you can't change the type of the actual variable.

like image 171
Some programmer dude Avatar answered Jan 30 '23 12:01

Some programmer dude