C++ 输出流操作符重载(输出容器的数据)

一、判断类型是否属于容器类型

template<typename T,typename... Types>
struct IsContainerType
{
	static const bool value = false;
};

template<typename T,typename... Types>
struct IsContainerType<std::vector<T, Types...>>
{
	static const bool value = true;
};

template<typename T,typename... Types>
struct IsContainerType<std::deque<T, Types...>>
{
	static const bool value = true;
};

template<typename T,typename... Types>
struct IsContainerType<std::set<T, Types...>>
{
	static const bool value = true;
};

template<typename T,typename... Types>
struct IsContainerType<std::multiset<T, Types...>>
{
	static const bool value = true;
};

template<typename K,typename V,typename... Types>
struct IsContainerType<std::map<K, V, Types...>>
{
	static const bool value = true;
};

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;

二、对pair类型输出流操作符重载

// we define operator << for std::pair used in the std::map
template<typename F,typename S>
std::ostream& operator<<(std::ostream& os, const std::pair<F, S>& p)
{
	os << "(" << p.first << ", " << p.second << ")";
	return os;
}

三、对容器类型输出流操作符重载

//template<typename,typename...> class Cntr 
template< template<typename,typename...> class Cntr,typename T,typename... Types>
std::enable_if_t<is_container<Cntr<T,Types...>>,std::ostream&>
operator<<(std::ostream& os, const Cntr<T, Types...>& cntr)
{
	if (!cntr.empty())
	{
		auto last_element = std::prev(cntr.end());
		os << "{";

		for (auto itr = cntr.begin(); itr != last_element; 
			itr = std::next(itr))
		{
			os << *itr << ", ";
		}

		os << *last_element << "}";
	}

	return os;
}

四、测试容器的输出流操作符重载

	std::vector<int> v{ 1,2,3,4,5,6,7,8,9,10 };
	std::cout << v << std::endl;

	std::set<int, std::greater<int>> s{ 1,2,3,4,5 };
	std::cout << s << std::endl;

	std::deque<char> dc{ 'a','b','c','d' };
	std::cout << dc << std::endl;

	std::map<std::string, int> m{ {"Trump",23},{"Moon",30},{"Han shuang",28},{"Liu sai",23} };
	std::cout << m << std::endl;

	std::string msg = "I love C++ template metaprogramming!";
	std::cout << msg << std::endl;

输出结果:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

{5, 4, 3, 2, 1}

{a, b, c, d}

{(Han shuang, 28), (Liu sai, 23), (Moon, 30), (Trump, 23)}

I love C++ template metaprogramming!

std::enable_if 的几种用法

std::enable_if 的几种用法_jeffasd的博客-CSDN博客_std::enable_if 对std::enable_if的解释以及使用!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值