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

一、定义是否是容器类型

#include 

#include 
#include    // std::enable_if 
#include   // std::pair
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 

// 默认类型为false
template
struct IsContainerType
{
	static const bool value = false;
};

// Vector类型为true
template
struct IsContainerType>
{
	static const bool value = true;
};

// deque类型
template
struct IsContainerType>
{
	static const bool value = true;
};

// set类型
template
struct IsContainerType>
{
	static const bool value = true;
};

// multiset类型
template
struct IsContainerType>
{
	static const bool value = true;
};

// map类型
template
struct IsContainerType>
{
	static const bool value = true;
};

// multimap类型
template
struct IsContainerType>
{
	static const bool value = true;
};

// 定义获取容器类型的模板
template
constexpr bool is_container = IsContainerType::value;

二、测试是否是容器类型

template
bool TestContainer(std::string name, const T& cntr)
{
	if (is_container)
	{
		std::cout << "Yes, " << name << " is a container!\n";
		return true;
	}
	else
	{
		std::cout << "No, " << name << " is not a container!\n";
		return false;
	}
}

测试实例

	std::vector v{ 1,2,3,4,5,6,7,8,9,10 };
	std::set s{ 1,2,3,4,5 };
	std::map m{ {"Trump",23},{"Moon",30},{"Han shuang",28},{"Liu sai",23} };
	std::string msg{ "hello container!" };

// 测试是否属于容器类型
if (is_container)
	{
		std::cout << "Yes,container\n";
	}
	else
	{
		std::cout << "No, not container\n";
	}

	if (is_container)
	{
		std::cout << "Yes,container\n";
	}
	else
	{
		std::cout << "No, not container\n";
	}

  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!

你可能感兴趣的:(C++,STL容器的类型)