检查stl容器中的元素类型 - c ++

Pat*_*ity 17 c++ containers types stl

我怎样才能获得STL容器所持有的元素类型?

Kea*_*eks 21

container::value_type
Run Code Online (Sandbox Code Playgroud)

  • @Patrick:你无法比较"value_type返回的值",因为value_type是一个类型,而不是一个值.因此,比较两个value_types是静态操作,而不是运行时操作.根据您要实现的目标,您可能需要查看Boost.TypeTraits中的"is_same":http://www.boost.org/doc/libs/1_40_0/libs/type_traits/doc/html/boost_typetraits/reference /is_same.html (2认同)
  • @Patrick:你要求存储在向量中的*type*元素,而不是元素的*value*.你可以比较这些值,你无法比较类型(至少没有很多元编程技巧) - 也许你应该解释一下你正在尝试做什么. (2认同)

Kir*_*sky 18

对于一般的容器,它将是X::value_type.对于关联容器,它将是X::mapped_type(X::value_type对应于pair<const Key,T>).这是根据C++标准的第23章.

要检查类型是否相等,您可以使用boost::is_same.

  • 更新:我们现在有了 [`std::is_same`](https://en.cppreference.com/w/cpp/types/is_same)。 (2认同)

Unc*_*ens 5

检查两个类型是否相同可以这样实现(没有 RTTI,值在编译时可用):

template <class T, class U>
struct same_type
{
    static const bool value = false;
};

//specialization for types that are the same
template <class T>
struct same_type<T, T>
{
    static const bool value = true;
};

//sample usage:
template <class FirstContainer, class SecondContainer>
bool containers_of_same_type(const FirstContainer&, const SecondContainer&)
{
    return same_type<
        typename FirstContainer::value_type, 
        typename SecondContainer::value_type
    >::value;
}

#include <vector>
#include <list>
#include <iostream>

int main()
{
    std::cout << containers_of_same_type(std::vector<int>(), std::list<int>());
    std::cout << containers_of_same_type(std::vector<char>(), std::list<int>());
}
Run Code Online (Sandbox Code Playgroud)

(这基本上是boost::is_same工作原理,减去某些编译器的解决方法。)