c++boostboost-phoenix

Problems adapting member functions in Phoenix


I use BOOST_PHOENIX_ADAPT_FUNCTION all the time in Spirit. I'd like to be able to adapt member functions for all of the same reason. However, I get compile errors if I do something like this:

struct A { int foo(int i) { return 5*i; }};

BOOST_PHOENIX_ADAPT_FUNCTION(int, AFoo, &A::foo, 2)

Is there an easy way to adapt a member function? Note that I can't just store a bind expression in an auto because I am on VC2008. How come it doesn't just work like in bind and function?

Thanks,

Mike


Solution

  • The BOOST_PHOENIX_ADAPT_FUNCTION(RETURN,LAZY_NAME,FUNC,N)is really simple. It just creates a functor with a templated operator() that returns RETURN and has N template parameters. In its body it simply invokes FUNC(PARAMETERS...). But &A::foo is not directly callable, and so your error occurs. You can use:

    BOOST_PHOENIX_ADAPT_FUNCTION(int,AFoo,boost::mem_fn(&A::foo),2)
    

    Running on Coliru

    #include <iostream>
    #include <boost/phoenix.hpp>
    #include <boost/phoenix/function.hpp>
    #include <boost/mem_fn.hpp>
    
    struct A {
        A(int f) : f_(f) {}
    
        int foo(int i) {
            return f_*i;
        }
      private: 
        int f_;
    };
    
    BOOST_PHOENIX_ADAPT_FUNCTION(int,AFoo,boost::mem_fn(&A::foo),2)
    
    int main() {
        using namespace boost::phoenix;
        using namespace boost::phoenix::arg_names;
    
        A instance(5);
        std::cout << AFoo(arg1,arg2)(&instance, 2) << std::endl;
    }