How to get element type from STL container instance?

NoSenseEtAl picture NoSenseEtAl · Sep 12, 2012 · Viewed 15k times · Source

I know about value_type, key_type... but they operate on types, not on instances. I tried stuff like :

std::set<uint64_t> mySet;   

decltype (mySet)::value_type pos;

But it doesnt work.

EDIT: I use VS 2010.

EDIT2: the prupose of this code was to get a type to give it to boost::lexical_cast<> is there a workaround that enables that ? I want something like this:

   mySet.insert(boost::lexical_cast<decltype(mySet)::value_type>(*it));
  // it is a iterator in vector of strings

EDIT3 : this works:

mySet.insert(boost::lexical_cast<decltype(mySet)::value_type>(*it));

Answer

user784668 picture user784668 · Sep 12, 2012

decltype (mySet)::value_type is correct. Make sure you have C++11 mode enabled in your compiler. If you have, then it's a compiler bug.

A possible workaround involves using the identity metafunction:

template <typename T>
struct identity { typedef T type; };

identity<decltype(mySet)>::type::value_type pos;