Question

I am reading sometimes about type determination in runtime based on typeid, I try the following code

#include <iostream>
#include <vector>
#include <typeinfo>

typedef std::vector<int> Vector;

template <class T> void foo(T &v)
{
  cout << typeid(Vector::value_type).name() << endl; // this is ok
  cout << typeid(T::value_type).name() << endl; // this doesn't compile
}

void main(void)
{Vector v;

 foo(v);
}

The above code compiles only when we put in the specific type into typeid, but it doesn't work if I use template T instead. So if I have a container v, how can I determine the value type in runtime? Thanks.

Was it helpful?

Solution

You need to use typename:

cout << typeid(typename T::value_type).name() << endl;

This has nothing to do with typeid. This is a general issue whenever you use a member of a class where the specific class you use depends on a template parameter. By default, the compiler assumes that all members of some unknown class T are not types. You have to explicitly tell it otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top