1

我正在尝试将函数对象列表应用于以下代码中的某个值。但是这段代码会导致 错误
boost_1_44\boost\fusion\algorithm\iteration\detail\for_each.hpp(82): error C2064:

如何将函数对象列表应用于某个值?

double doublef2(double x,double y){return 2*x+y; }
double doublef3(double x,double y){return 3*x*y; }
double doublef4(double x,double y){return 4+x*y; }
main(){
    boost::fusion::vector<
        boost::function<double (double,double)>,
        boost::function<double (double,double)>,
        boost::function<double (double,double)>
       > tt;


    boost::fusion::at_c<0>(tt)= & doublef2;
    boost::fusion::at_c<1>(tt)= & doublef3;
    boost::fusion::at_c<2>(tt)= & doublef4;

boost::fusion::for_each(tt, std::cout << boost::lambda::_1(10,100) << '\n');

}
4

2 回答 2

2

您的问题与 boost.fusion 完全无关。相反,您的问题是由于尝试从 boost.lambda 仿函数调用非惰性仿函数(不使用bind)引起的。使用boost::fusion::for_each适当的仿函数而不是 boost.lambda 仿函数可以获得您期望的结果:

#include <iostream>
#include <boost/function.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/for_each.hpp>

double doublef2(double x, double y) { return 2. * x + y; }
double doublef3(double x, double y) { return 3. * x * y; }
double doublef4(double x, double y) { return 4. + x * y; }

struct proper_functor
{
    typedef void result_type;

    proper_functor(double x, double y) : x_(x), y_(y) { }

    template<typename F>
    void operator ()(F const& f) const { std::cout << f(x_, y_) << '\n'; }

private:
    double x_, y_;
};

int main()
{
    boost::fusion::vector<
        boost::function<double (double, double)>,
        boost::function<double (double, double)>,
        boost::function<double (double, double)>
    > tt;

    boost::fusion::at_c<0>(tt) = doublef2;
    boost::fusion::at_c<1>(tt) = doublef3;
    boost::fusion::at_c<2>(tt) = doublef4;

    boost::fusion::for_each(tt, proper_functor(10., 100.));
}

顺便说一句,在实际代码中遇到这种 boost.fusion 的用法会很奇怪;fusion 容器适用于同质类型,如果您使用所有相同的类型,请改用//std::array并为自己节省一些编译时间。std::tr1::arrayboost::array

于 2011-03-25T08:10:52.983 回答
0

正如ildjarn提到的,将函数调用运算符()直接应用于 lambda::placeholders似乎无法以某种方式工作。在这种情况下可能lambda::bind会达到目的。
例如:

fusion::for_each(tt, cout << lambda::bind( lambda::_1, 10, 100 ) << '\n')

希望这可以帮助

于 2011-03-25T08:33:46.047 回答