Title: How do I get the template type of a given element at runtime in C++?
Tags: c++;templates;polymorphism
Question: I'm designing a simple Array class with the capability of holding any type of object, like a vector that can hold multiple types of data in one object. (This is for learning purposes.)
I have an empty base class called Container:
class Container {};
And a templatized subclass called Object:
template <class T&gt;
class Object : public Container {
T&amp; object;
public:
Object(T&amp; obj = nullptr) : object(obj) {}
I have an Array class which holds a vector of pointers to Containers which I use to hold Objects:
class Array {
st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0vector<Container *&gt; vec;
public:
template <class T&gt;
void add_element(const T&amp;);
auto get_element(int);
add_element stores elements into Objects and puts them into vec:
template <class T&gt;
void Array75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0_element(const T&amp; element)
vec.push_back(new Object<T&gt;(element));
get_element removes the element from it's Object and passes it back to the caller. This is where my problem lies. In order to remove the element from the Object, I need to know what type of Object it is:
auto Array75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0get_element(int i)
return (Object</* ??? */&gt; *)vec[i])-&gt;object;
Is there some way for me to find out what sort of object I'm storing?
Edit: since people are claiming that this is not possible, how about this. Is there some way of actually storing type information inside of a class? (I know you can do that in ruby). If I could do that, I could store the return type of get_element in each Object.
Comment: @MichaelDorst: you *can't* store types as variables.

Comment: Go have a look at [boost75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0ny](http://stackoverflow.com/questions/4988939/how-do-boostvariant-and-boostany-work)

Comment: May I ask why you are using `nullptr` as the default value of the `obj` parameter in `Object`'s constructor? When you don't provide any argument to the constructor, this is going to fail, isn't it?

Comment: @MichaelDorst Edit: since people are claiming that this is not possible, how about this. Is there some way of actually storing type information inside of a class? (I know you can do that in ruby). If I could do that, I could store the return type of get_element in each Object.
In class Object you can save template parameter by typedef, e.g. typedef T object_type; but it can`t help you.

Comment: Each instantiation of template class with different type have own fiels, so, for Object object_type will be st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0string, for Object object_type will be int etc, also we can declare static variable of such type, but i can`t understood how it can helps you... There is no Reflection in standart C++, so, only RTTI rest.

Comment: @mfontanini This shouldn't even compile.

Comment: @ildjarn: Since the OP is using `auto` in the question, I think it's safe to assume that.

Comment: @user315052 because It'd be harder to use that way. @ildjarn Yes it does, but if I `decltype(vec[i])` I'll just get a `Container *`. I need to know what subclass it is.

Comment: @ForEveR how is that storing type information? that will only work once (you can't typedef multiple types to the same identifier e.g. `typedef T obj_type; ... typedef Q obj_type;`) and I need it to work for every element I add to my `Array`.

Comment: @ForEveR Also, I don't think you can `typedef` inside of a function. `typedef` is a compile-time thing.

Comment: @ForEveR So what is the syntax for storing types as variables? It can't be `typedef` can it? I thought `typedef` defined a new type not a variable...

Here is the accepted answer: I was thinking something along the lines of this template for your get_element.
template <class T&gt;
T&amp; Array75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0get_element(int i, T &amp;t)
Object<T&gt; *o = dynamic_cast<Object<T&gt; *&gt;(vec[i]);
if (o == 0) throw st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0invalid_argument;
return t = o-&gt;object;
Array arr;
double f;
int c;
arr.get_element(0, f);
arr.get_element(1, c);
But alternatively, you could use this:
template <class T&gt;
T&amp; Array75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0get_element(int i)
Object<T&gt; *o = dynamic_cast<Object<T&gt; *&gt;(vec[i]);
if (o == 0) throw st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0invalid_argument;
return o-&gt;object;
f = arr.get_element<double&gt;(0);
c = arr.get_element<int&gt;(1);
Comment for this answer: @MichaelDorst: Edit made, regards
Comment for this answer: @MichaelDorst: I saw your edit suggestion. So you are okay with users of your `Array` to call it like `double f = arr.get_element(i)`? Because, I thought `arr.get_element(i, f)` was nicer.
Comment for this answer: @MichaelDorst: Gotcha. Happy hacking!
Comment for this answer: @MichaelDorst: when you implement your `operator []`, use the technique described [here](http://stackoverflow.com/questions/9957936/c-array-subscript-operator-template).
Comment for this answer: I don't really like your throw statement, generally I would throw a `st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0exception`, but your basic idea is good. No prb - thx =)
Comment for this answer: well then I would have to make a dummy variable every time I called it. That seems silly. better to just specify the type.
Comment for this answer: also, I will be overloading `operator []` later, so I'll want the call to be `vec[i];` not `vec[i, f];`. I'm actually not sure if the latter is possible. It's also more clear that I'm casting to `double` if I use it that way.

Here is another answer: dynamic_cast<>(), when used on a pointer, can be used to check whether the cast is actually possible since it returns NULL when the types don't match.
However, you'll probably want to reconsider your setup; dynamic_cast isn't something you'll want to use if you can avoid it, and having cascades of "if object-is-type1 then do this; else if object-is-type2 then do that; else if object-is-type3..." is almost always a sure sign of bad design.
Using auto in your get_element is probably your trick of getting around the problem that you don't know what the type will be -- that won't work, though. The compiler still has to know the return type; it cannot xmurillo@example.org.
EDIT: you might also go a step back and ask yourself whether you REALLY need an array that can store "anything". I've used Objective-C for a long time, and it's basically built around the idea that everything is just an "object" and people can call anything on anything, it's all sorted xmurillo@example.org. However, I found that actual uses of this are rare... and for containers in particular, I find that every NSArray that I use only has objects of one type, or maybe of a common base class, but not actually distinct, unrelated classes.
Comment for this answer: The uses are rare, but it's still necessary to have that capability. My original idea was to make a class that I could use as a wrapper around Obj-C objects (to minimize Obj-C++ code since it's hard to maintain). If I use a vector I can't handle every scenario, which is problematic.

Here is another answer: The return type of a function like Array75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0get_element must be determined at compile time.  Since class Array does not know what types of containers it stores at compile time, the only option is to just return the base Container* pointer.  Then users of that code can use virtual functions and/or dynamic_cast to deal with those generalized containers.
Comment for this answer: The whole point of this class was so that I wouldn't have to use all that syntax every time I want to access an element. `((Object *)vec[num].->object` is just too messy.
Comment for this answer: If `Container` has enough virtual functions, you don't need any casts.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 11, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:07/06/12', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<c++><templates><polymorphism>', 'Title': 'How do I get the template type of a given element at runtime in C++?', 'ViewCount': 1511, 'id': 11370340, 'user_AboutMe': "<p>I'm a Computer Science student at Sacramento State University, and I graduate in Spring 2020. I enjoy helping others learn to code - I find it both fun and instructive.</p>\n", 'user_AccountId': 1352981.0, 'user_DisplayName': 'Michael Dorst', 'user_Reputation': 7640.0, 'user_Views': 878.0, 'user_id': 1291990.0}}