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

How to Deserialize a list of objects from json in flutter

8  Asked on January 28, 2021 by gainz


How to pass input variable in structure directive?

1  Asked on January 27, 2021 by alice-messis


How to iterate over a list of floats in python

4  Asked on January 27, 2021 by joeyhoward988


Can I run docker system prune -a without downtime

1  Asked on January 27, 2021 by aswin-george


Calculating total Price of groceries with execptions in Python

4  Asked on January 27, 2021 by shemtheultimate


handling multiple useState inside conditional ternary

2  Asked on January 27, 2021 by kachi-cheong


react-native existing app crash on Android 4.1

0  Asked on January 27, 2021 by s-leg3ndz


HTML table widths set proportionally

1  Asked on January 27, 2021 by mayur-arora


Alsa issues on Raspberry pi

1  Asked on January 27, 2021 by suraj-hebbar-shankar


How to merge dictionaries with the same key and value in Python

1  Asked on January 26, 2021 by arbin-bulaybulay


AJAX switching HTML

1  Asked on January 26, 2021 by mimi


Using request to return a json value

1  Asked on January 26, 2021 by gta-sprx


Ask a Question

Get help from others!

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