一、定义是否是容器类型
#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>
// 默认类型为false
template<typename T,typename... Types>
struct IsContainerType
{
static const bool value = false;
};
// Vector类型为true
template<typename T,typename... Types>
struct IsContainerType<std::vector<T, Types...>>
{
static const bool value = true;
};
// deque类型
template<typename T,typename... Types>
struct IsContainerType<std::deque<T, Types...>>
{
static const bool value = true;
};
// set类型
template<typename T,typename... Types>
struct IsContainerType<std::set<T, Types...>>
{
static const bool value = true;
};
// multiset类型
template<typename T,typename... Types>
struct IsContainerType<std::multiset<T, Types...>>
{
static const bool value = true;
};
// map类型
template<typename K,typename V,typename... Types>
struct IsContainerType<std::map<K, V, Types...>>
{
static const bool value = true;
};
// multimap类型
template<typename K,typename V,typename... Types>
struct IsContainerType<std::multimap<K, V, Types...>>
{
static const bool value = true;
};
// 定义获取容器类型的模板
template<typename T,typename... Types>
constexpr bool is_container = IsContainerType<T, Types...>::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,container
Yes,container
Yes, 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!