如何从STL容器实例中获取元素类型?

NoS*_*tAl 15 c++ stl decltype c++11

我知道value_type,key_type ......但它们是在类型上运行,而不是在实例上运行.我试过像这样的东西:

std::set<uint64_t> mySet;   

decltype (mySet)::value_type pos;
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

编辑:我使用VS 2010.

EDIT2:这段代码的目的是得到一个类型来赋予它boost :: lexical_cast <>是否有一种解决方法可以实现这一点?我想要这样的东西:

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

编辑3:这有效:

mySet.insert(boost::lexical_cast<decltype(mySet)::value_type>(*it));
Run Code Online (Sandbox Code Playgroud)

小智 17

decltype (mySet)::value_type是正确的.确保在编译器中启用了C++ 11模式.如果你有,那么这是一个编译器错误.

可能的解决方法涉及使用标识元函数:

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

identity<decltype(mySet)>::type::value_type pos;
Run Code Online (Sandbox Code Playgroud)


Pet*_*ker 7

我会以相反的方式做到这一点:

typedef std::set<uint_least64_t> set_type;
set_type mySet;
set_type::value_type pos;
Run Code Online (Sandbox Code Playgroud)