我想使用c++容器的
我正在尝试编写一个成员函数来检测后面一种类型的容器,但它不能正常工作。以下是我的代码:
::iterator
成员类型将它们解析到另一个对象中。迭代器成员类型指向单一类型对象的容器(如向量、队列等)将转换为类似列表的对象,而迭代器成员类型指向std::pair
的容器将转换为类似于映射的对象。我正在尝试编写一个成员函数来检测后面一种类型的容器,但它不能正常工作。以下是我的代码:
#include <tuple>
#include <iterator>
#include <type_traits>
template <typename T>
struct is_pair : std::false_type { };
template <typename T, typename U>
struct is_pair<std::pair<T, U>> : std::true_type { };
template <typename T>
constexpr bool is_pair_v = is_pair<T>::value;
template <typename...>
struct is_mapping : std::false_type { };
template <typename Container>
struct is_mapping<Container, std::enable_if_t<
is_pair_v<std::iterator_traits<typename Container::iterator>::value_type>
>> : std::true_type { };
template <typename T>
constexpr bool is_mapping_v = is_mapping<T>::value;
#include <map>
#include <vector>
#include <iostream>
int main() {
std::cout << "is_pair:" << std::endl;
std::cout << "Map: " << is_pair_v<std::iterator_traits<std::map<int, int>::iterator>::value_type> << std::endl;
std::cout << "Vector: " << is_pair_v<std::iterator_traits<std::vector<int>::iterator>::value_type> << std::endl;
std::cout << std::endl;
std::cout << "is_mapping:" << std::endl;
std::cout << "Map: " << is_mapping_v<std::map<int, int>> << std::endl;
std::cout << "Vector: " << is_mapping_v<std::vector<int>> << std::endl;
}
由于某些原因,is_mapping_v
总是为 false,代码的输出结果如下:
$ g++ -std=c++14 temp.cc && ./a.out
is_pair:
Map: 1
Vector: 0
is_mapping:
Map: 0
Vector: 0
我的代码哪里出问题了?
注意:这不是检查类型是否为map的重复问题。那个问题的答案使用::key_type
和::mapped_type
成员来检测map(但对于像std::multimap
这样的类失败)。我还明确使用迭代器指向后面的std::pair
,因此检查它更有意义。