if I have a template:
template <class T>
struct Item
{
T _value;
};
I can then do:
// ...
Item<int> x = { 42 }; // declared as an int
// ...
decltype(x._value) y = 20; // 'y' is also an int
But is it possible to store the decltype
to a variable so it can be used later?
Why?
I want to store the values of items as pointer.
Something like std::vector<Item*>
but as they are templates I have to store them as pointers to void
:
std::vector<void*> is;
is.push_back(new Item<int>());
is.push_back(new Item<double>());
is.push_back(new Item<float>());
And this is all fine, but when it comes time to delete the pointer I need to re-cast my void*
back to the proper type (so the destructors are called):
delete (Item<int>*)is[0];
And if I know the type, I could do:
delete (Item<decltype(whatever)>*)is[0];
Hence the reason I would need to store the decltype
.
I hope this makes sense.
std::variant
andstd::any
). They are probably better implementations of what you need.void*
, in C++ is done withstd::any
and the visitor pattern. The smart pointer solutions in fact use a some kind of type erasure internally.Item<T>
which has a virtual destructor?