目前, boost::fusion::for_each 迭代单个序列的元素。我正在尝试创建一个以类似方式工作但具有许多序列的函数,并将迭代序列之间的所有可能组合。
例如,如果我有三个序列 S1、S2、S3,我想创建一个这样的函子
struct my_functor {
template <class x, class y, class z>
void operator()(x& el1, y& el2, z& el3) {...}
}
然后打电话
for_each(s1, s2, s3, my_functor()) // applies the functor to all combinations of elements of s1, s2, s3
其中 s1, s2, s3 是 S1, S2, S3 的实例。
我首先为一般情况(任意数量的序列)编写代码,但发现它太难了。所以我决定从两个序列开始,然后从那里开始。当我有两个序列(为简单起见假设 fusion::vectors )时,我已经设法完成了,如下所示:
//for_each.hpp
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/back.hpp>
#include <boost/mpl/size.hpp>
template <class Seq1, class Seq2, int i1, int i2, class F>
struct my_call {
static void apply(Seq1& seq1, Seq2& seq2, F& f) {
f(boost::fusion::at_c<i1>(seq1), boost::fusion::at_c<i2>(seq2)); // apply functor for a given pair of ints
my_call<Seq1, Seq2, i1, i2+1, F>::apply(seq1, seq2, f); // increase second int by 1 and apply functor again
}
};
// terminal condition for 2nd sequence
template <class Seq1, class Seq2, int i1, class F>
struct my_call<Seq1, Seq2, i1, boost::mpl::size<Seq2>::type::value - 1, F> {
static void apply(Seq1& seq1, Seq2& seq2, F& f) {
f(boost::fusion::at_c<i1>(seq1), boost::fusion::back(seq2));
my_call<Seq1, Seq2, i1+1, 0, F>::apply(seq1, seq2, f); // reset 2nd int and increase 1st by 1
}
};
// terminal condition for both sequences
template <class Seq1, class Seq2, class F>
struct my_call<Seq1, Seq2, boost::mpl::size<Seq2>::type::value - 1, boost::mpl::size<Seq2>::type::value - 1, F> {
static void apply(Seq1& seq1, Seq2& seq2, F& f) {
f(boost::fusion::back(seq1), boost::fusion::back(seq2));
}
};
// the actual function
template <class Seq1, class Seq2, class F>
void for_each(Seq1& seq1, Seq2& seq2, F& f) {
my_call<Seq1, Seq2, 0, 0, F>::apply(seq1, seq2, f);
}
和主要作为
//main.cpp
#include "for_each.hpp"
#include <iostream>
struct myf {
template <class X, class Y>
void operator()(X& x, Y& y) {
std::cout << x + y << std::endl;
}
};
int main() {
boost::fusion::vector<int, double> x(1, 2.5);
boost::fusion::vector<double, int> y(2, 5);
myf F;
for_each(x, y, F);
return 0;
}
我的主要(没有双关语)问题是概括上述内容以使其适用于任意数量的序列。非常欢迎任何建议!谢谢