我找到了以下代码,我将其用作基础。它描述了如何使用值 6 填充 boost::fusion::vector:
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
struct F {
F(int blah): blah(blah){}
template <typename T>
void operator()(T& t) const {
t = blah;
}
int blah;
};
template <typename T>
void apply_for_each_to_assign(T &t)
{
boost::fusion::for_each(t, F(6));
}
int main() {
boost::fusion::vector<int, double, int> idi;
apply_for_each_to_assign(idi);
}
我的问题是,不是用值 6 填充每个元素 - 让每个元素递增 1 的最简洁方法是什么?所以
v[0] = 1
v[1] = 2
等等?我想我需要编写一个增量函数,但我不确定如何将它合并到上面的代码中?
最佳答案
您可以使用fold
.
fold
采用函数 A f(A, B)
,其中 B
是您的元素类型,初始 A
value 并在所有元素上调用它。它大致相当于 f(f(f(initial,first_elem), secondary_elem),third_elem)
。
你应该像这样声明仿函数:
struct accumulator
{
typedef int result_type;
template<typename T>
int operator()(int value, T& t) const
{
t += value;
return value + 1;
}
};
用法如下:
template <typename T>
void apply_for_each_to_assign(T &t)
{
boost::fusion::fold(t, 1, accumulator());
}
这是一个完整的打印示例:
#include <boost/fusion/algorithm/iteration/fold.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/fold.hpp>
#include <boost/fusion/container.hpp>
#include <iostream>
struct accumulator
{
typedef int result_type;
template<typename T>
int operator()(int value, T& t) const
{
t += value;
return value + 1;
}
};
struct Print {
template <typename T>
void operator()(T& t) const {
std::cout << t << std::endl;
}
};
template <typename T>
void apply_for_each_to_assign(T &t)
{
boost::fusion::fold(t, 1, accumulator());
boost::fusion::for_each(t, Print());
}
int main()
{
boost::fusion::vector<int, double, int> idi;
apply_for_each_to_assign(idi);
}
关于c++ - 传入一个递增 boost::fusion:vector 元素的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685755/