C++序列解包打印STL容器
/*IsOverloadOsOperator为判断数据类型是否定义了输出流函数,void_t在C++14中才存在*/
/*type_tt::IsOverloadOsOperator<std::string>::value adjust if define <<*/
template <typename...Ts> using void_t=void;
template <typename T,typename =void_t <>>
struct IsOverloadOsOperator:std::false_type{};
template <typename T>
struct IsOverloadOsOperator<T,void_t<decltype(*(std::ostream *) nullptr<<std::declval<T>())>
>:std::true_type{};
template<typename T>
std::ostream& print(std::ostream &out,T const &val) {
return (out << val << " ");
}
template<template<typename,typename...> class TT,typename... Args>
std::ostream& operator<<(std::ostream &out,TT<Args...> const &cont);
template<typename T1,typename T2>
std::ostream& print(std::ostream &out,std::pair<T1,T2> const &val) {
return (out << "{" << val.first << ":" << val.second << "}");
}
template<template<typename,typename...> class TT,typename... Args>
std::ostream& operator<<(std::ostream &out,TT<Args...> const &cont) {
out<<"[";
for(auto&& elem : cont) {
print(out, elem);
}
out<<"]";
return out;
}
/*problem in print function,not generic*/
template <typename T>
void print(const T &lastArg){
std::cout<<lastArg<<"\n";
}
template <typename T,typename ... Types>
void print(const T &firstArg, const Types&... args){
if(IsOverloadOsOperator<T>::value) {
std::cout << firstArg << std::endl;/*replace cout with LOG(INFO)*/
print(args...);
}
}
测试代码
std::map<int,std::vector<std::pair<int ,int >>> m;
m.insert(std::make_pair<int,std::vector<std::pair<int ,int >>>(13,std::vector<std::pair<int ,int >>{std::make_pair<int ,int >(10,20),std::make_pair<int ,int >(10,20)}));
print("1",m,10);
输出:
1
[{13:[{10:20}{10:20}]}]
10