使用boost::hana::scan_left进行累加操作
boost::hana是C++14的一个模板库,提供了模板元编程的工具和函数式编程支持。scan_left是其中一个非常有用的函数,在对数组或者元组中的元素进行累加或者累乘时非常方便。
我们看下面这段代码:
#include <boost/hana.hpp>
#include <string>
#include <iostream>
int main() {
auto xs = boost::hana::make_tuple(1, 2, 3, 4, 5);
auto ys = boost::hana::make_tuple(std::string{"a"}, std::string{"b"}, std::string{"c"});
// 求和
auto sum = boost::hana::scan_left(xs, 0, [](auto acc, auto x) { return acc + x; });
std::cout << "sum: " << sum << std::endl;
// 拼接字符串
auto str = boost::hana::scan_left(ys, std::string{""}, [](auto acc, auto x) { return acc + x; });
std::cout <