C++:有没有办法从实例模板中提取类型?

sqd*_*sqd 0 c++ templates

//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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,将元素的类型放入模板参数是非常愚蠢的,因为它已经包含在容器的类型中.

那么,从T中获取元素的类型是否有任何魔力?

很多Thx :-)

Nia*_*all 5

如果容器是标准库容器,则元素的名称是容器的嵌入名称,如下所示:

typedef typename T::value_type type;
Run Code Online (Sandbox Code Playgroud)

标准容器中有一些标准名称(例如,参见cppreference上的vector)和C++标准 §23.2.

X::value_type
X::reference
X::const_reference
X::iterator
X::const_iterator
X::difference_type
X::size_type
Run Code Online (Sandbox Code Playgroud)