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
    void *value;
    template <typename T>
    Value(T v)
        value = new T(v);


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

One Answer


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!

Related Questions

Bluehost hosted React pages not found

0  Asked on November 10, 2021 by paul-lindberg


Change a view margins programmatically

4  Asked on November 10, 2021 by m-r_dino


React returning view from switch statement

1  Asked on November 10, 2021 by mattblack


Find string then return different row value Python

0  Asked on November 10, 2021 by newtothecrew


React JS – route does not pick the required Component

0  Asked on November 10, 2021 by nirjal-paudel


get character after space of array value on javascript

9  Asked on November 7, 2021 by riko-pramayudi


Ask a Question

Get help from others!

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