一、定义是否是容器类型
#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类型为truetemplate
二、测试是否是容器类型
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容器的类型】
推荐阅读
- 如何确保数据与人工智能的完整性?
- 如何修改WordPress后台的登录界面?
- golang如何将http请求流转到gin
- 如何购买一台性价比较高的电脑
- SQL如何删除重复数据
- 如何去掉电脑桌面的小黄锁?
- 春季呼吸道疾病高发 老人小孩如何预防感冒
- 肝好不好看身体6部位 春季如何巧补肝
- 红茶柠檬的功效,红茶和柠檬蜂蜜的功效与作用
- 房屋未住物业费如何收?