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);
}
};
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
4 Asked on November 10, 2021 by m-r_dino
1 Asked on November 10, 2021 by carboneum
1 Asked on November 10, 2021 by josh-loecker
1 Asked on November 10, 2021 by mattblack
2 Asked on November 10, 2021 by swing1234
5 Asked on November 10, 2021 by eskimo4
2 Asked on November 10, 2021 by abdi
0 Asked on November 10, 2021 by newtothecrew
1 Asked on November 10, 2021 by eli-turasky
1 Asked on November 10, 2021 by anu-john
1 Asked on November 10, 2021
1 Asked on November 10, 2021 by abie
amazon dynamodb amazon dynamodb data modeling amazon dynamodb index dynamodb queries
0 Asked on November 10, 2021 by nirjal-paudel
1 Asked on November 10, 2021 by rfkid
0 Asked on November 10, 2021 by felixc
4 Asked on November 7, 2021 by gringo
9 Asked on November 7, 2021 by riko-pramayudi
1 Asked on November 7, 2021 by tiredwater
Get help from others!
Recent Answers
Recent Questions
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP