Fold expressions is the extension for already introduced variadic templates in C++11.
It allows to pack and unpack template parameters in unary and binary operations.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
template<typename ... Args> auto Sum(Args... args) { return (args + ...);} template<typename ... Args> bool all(Args ... args) { return (args && ...);} template<typename ... Args> void printer(Args ... args){ (std::cout << ... << args) << std::endl; } int main() { std::cout << all(true, true, true) << std::endl; printer(1, 2, 3); std::cout << Sum(1, 2, 3, 4, 5) << std::endl; return 0; } |
Example with pushing values:
|
template<typename T, typename ... Args> void push_all(std::vector<T>& vector, Args ... args) { (vector.push_back(args), ...); } int main() { std::vector<int> vector_ = { 1, 2, 3, 4, 5 }; push_all(vector_, 1, 1, 1, 2,22, 2,2); for (auto value : vector_) std::cout << value << " "; return 0; } |
Continue reading “C++17: Fold expressions”