C++ 如何判断一个类型是STL容器的类型

一、定义是否是容器类型
#include <IOStream>#include <string>#include <type_traits>// std::enable_if #include <utility>// std::pair#include <functional>#include <vector>#include <deque>#include <list>#include <set>#include <map>#include <unordered_set>#include <unordered_map>// 默认类型为falsetemplate<typename T,typename... Types>struct IsContainerType{ static const bool value = https://www.isolves.com/it/cxkf/yy/C/2022-03-15/false;};// Vector类型为truetemplatestruct IsContainerType>{ static const bool value = true;};// deque类型templatestruct IsContainerType>{ static const bool value = true;};// set类型templatestruct IsContainerType>{ static const bool value = true;};// multiset类型templatestruct IsContainerType>{ static const bool value = true;};// map类型templatestruct IsContainerType>{ static const bool value = true;};// multimap类型templatestruct IsContainerType>{ static const bool value = true;};// 定义获取容器类型的模板templateconstexpr bool is_container = IsContainerType::value;二、测试是否是容器类型
template<typename T>bool TestContainer(std::string name, const T& cntr){ if (is_container<T>) {std::cout << "Yes, " << name << " is a container!n";return true; } else {std::cout << "No, " << name << " is not a container!n";return false; }}测试实例
std::vector<int> v{ 1,2,3,4,5,6,7,8,9,10 }; std::set<int> s{ 1,2,3,4,5 }; std::map<std::string, int> m{ {"Trump",23},{"Moon",30},{"Han shuang",28},{"Liu sai",23} }; std::string msg{ "hello container!" };// 测试是否属于容器类型if (is_container<decltype(v)>) {std::cout << "Yes,containern"; } else {std::cout << "No, not containern"; } if (is_container<decltype(m)>) {std::cout << "Yes,containern"; } else {std::cout << "No, not containern"; }TestContainer("v", v); TestContainer("s", s); TestContainer("m", m); TestContainer("msg", msg); int a = 6; TestContainer("a", a);// 测试结果Yes,containerYes,containerYes, v is a container!Yes, s is a container!Yes, m is a container!No, msg is not a container!No, a is not a container!
【C++ 如何判断一个类型是STL容器的类型】


    推荐阅读