一、判断类型是否属于容器类型
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的解释以及使用!