我有两个元组,一个包含值,另一个元组包含这些值的操作。现在我想对每个值应用相应的操作,尽可能少的代码“开销”。类似于下面的简化示例。
#include <iostream>
#include <boost/hana.hpp>
namespace hana = boost::hana;
using namespace hana::literals;
struct ThinkPositive
{
void operator()(int &val) const
{
std::cout << "Think positive!\n";
val = std::abs(val);
}
};
struct Nice
{
void operator()(int &val) const
{
std::cout << val << " is nice!\n";
}
};
void numbers()
{
auto handlers = hana::make_tuple(Nice{}, ThinkPositive{});
auto nums = hana::make_tuple(5, -12);
auto handlers_and_nums = hana::zip(handlers, nums);
hana::for_each(handlers_and_nums, [](auto &handler_num) {
handler_num[0_c](handler_num[1_c]);
});
auto result = hana::transform(handlers_and_nums, [](const auto &handler_num) {
return handler_num[1_c];
});
hana::for_each(result, [](const auto num) {
std::cout << "got " << num << '\n';
});
}
int main()
{
numbers();
}
虽然上面的示例有效,但修改 nums 的内容会更好。
有没有办法修改 nums 到位?