C++模板元编程
- 变参模板(variadic template)
- 模板特化(templtion specialization)
- 参数包(parameter pack)
- sizeof... 运算符(sizeof... operator)
- 非类型模板参数(non-type template parameter)
打印 std::tuple<> 中的各个元素
//! 辅助模板 PrintHelper
template<std::size_t sz, std::size_t idx, class ...Args>
struct PrintHelper {
static void print(const std::tuple<Args...> &t) {
std::cout << idx << ": " << std::get<idx>(t);
std::cout << (idx + 1 == sz ? "" : ", ");
PrintHelper<sz, idx + 1, Args...>::print(t);
}
};
//! 辅助模板 PrintHelper的偏特化版本(当idx==sz时,终止对PrintHelper::print函数的递归调用)
template<std::size_t sz, class ...Args>
struct PrintHelper<sz, sz, Args...> {
static void print(const std::tuple<Args...> &t) {
// nothing to do
// recursively template ending...
}
};
template<class ...Args>
std::ostream &operator<<(std::ostream &out, const std::tuple<Args...> &t) {
constexpr auto TUPLE_SIZE = sizeof...(Args);
std::cout << "[";
PrintHelper<TUPLE_SIZE, 0, Args...>::print(t);
std::cout << "]";
return out;
}