//a class template to do something to STL container
template<typename T/*should be a STL container*/,typename Ele/*the type of element*/>
struct foo{
T a_container_with_an_element(){
T con;
Ele e;
con.push_back(++++e);
return con;
}
如您所见,将元素的类型放入模板的参数中是非常愚蠢的,因为它已经包含在容器的类型中。
那么,有什么魔法可以从 T 中获取元素的类型吗?
非常感谢 :-)
最佳答案
如果容器是标准库容器,则元素的名称是容器的嵌入名称,如下所示:
typedef typename T::value_type type;
标准容器中有一些标准名称(例如,参见 vector on cppreference )和 C++ standard §23.2.
X::value_type
X::reference
X::const_reference
X::iterator
X::const_iterator
X::difference_type
X::size_type
关于C++:有没有办法从实例化模板中提取类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25288727/