Yes, this is possible in C++.
The easiest solution is to use std::any
.
I'm not sure why you are asking about static variables however. Your array containing elements of type std::any
need not be static.
You would also probably prefer to use a std::vector
rather than an array.
Clarification
If you want something which you can access using 2 dimensions, you can easily accomplish thing using a vector of a vector.
std::vector<std::vector<TYPE>> my_2d_container;
// You initialize it like this:
// Create a vector
std::vector<TYPE> tmp;
tmp.push_back(... something ...); // repeat for each element
// Move the vector in the vector of vectors
// Note using `std::move` is an optimization. You can't use `tmp`
// again after doing this because the memory it references
// (effectively) no longer exists. But this is really quite advanced
// C++, so you could remove the `move` operation
my_2d_container.push(std::move(tmp));
To use std::any
is easy. You just use std::any_cast
in a try-catch, and deal with instances of std::bad_any_cast
which tells you when you are trying to get an object of the wrong type.
See the docs for more information. https://en.cppreference.com/w/cpp/utility/any
You could probably also explicitly check the type using the type()
function as part of a if statement. This might be faster. My preference is for the try-catch
.
Further information and polymorphism
There's also ways to accomplish what you want using polymorphism. In this case, everything you want to insert into the container has to inherit from some base type.
Whether or not this is a good idea for your particular use case is heavily dependent on the details of what you are doing. In general, you cannot and should not implement a pattern like this because you will end up with all sorts of strange code behaviour whereby multiple unrelated types all inherit from the same base type. Hence, you should use the std::any
type-erasure solution which is already provided to you.
There are also more advanced type-erasure techniques, but in order to implement such things you really need to be very familiar with design patterns theory. This is really not easy stuff.
Alternatives: Use another language
C++ is a strongly typed, statically typed language. It does not provide easy to use language features to support what you want to do.
What you really want is a dynamically typed language, such as python, which will easily allow you to implement the pattern you want to implement.
Alternatives would be Java, where every object inherits from Object
. So while Java is a statically typed language, it is intrinsically much easier to what you want in Java, compared to C++.
The reason C++ is the way it is? Speed. The compiler can produce highly optimized code because all the types you use are minimal in their memory footprint/size. If you take the polymorphic or type erasure approach, expect a performance penalty. But this probably isn't something you care about.