TransWikia.com

Is there a way to store a template variable from constructor for later use? (c++)

Stack Overflow Asked on August 2, 2020

I have a value class that should store any type of data. My constructor is a template and initializes a member void pointer variable with the value passed in. I need a method that returns the value with the void pointer cast to the correct data type. The current code doesn’t work but it shows what I want to do. This would work if I had the template on the whole class but I can’t do that because of how it’s being used elsewhere in the program. Is there a way to store the datatype for later use?

class Value
{
private:
    void *value;
public:
    Value()
    {
    }
    
    template <typename T>
    Value(T v)
    {
        value = new T(v);
    }

    ~Value()
    {
    }

    T getValue()
    {
        return *((T*)value);
    }
};

One Answer

No.

In C++ the type must be known at compile time. What you can do is having a template call that, if the caller provides the correct type, will return the object.

Something like

template<typename T>
T getValue() {
    return *(T*)value;
}

You can also add a check that if the provided type is wrong you generate a runtime error (using typeid, for example).

Answered by 6502 on August 2, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP