Kea*_*eks 21
container::value_type
Run Code Online (Sandbox Code Playgroud)
Kir*_*sky 18
对于一般的容器,它将是X::value_type.对于关联容器,它将是X::mapped_type(X::value_type对应于pair<const Key,T>).这是根据C++标准的第23章.
要检查类型是否相等,您可以使用boost::is_same.
检查两个类型是否相同可以这样实现(没有 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工作原理,减去某些编译器的解决方法。)