简体   繁体   中英

boost function bind compiled with a conversion error

I have the following code

#include <boost/function.hpp>
#include <boost/bind.hpp>

class Foo {    
    public:
    int getIfoo();
};

int Foo::getIfoo() {
    return 5;
}

int main () {

    boost::function<int (Foo)> getIntFoo;
    getIntFoo = boost::bind( &Foo::getIfoo, _1 );

    return 0;
}

When I compile with the following command g++ TestBoostBind.cpp I've got the following error

/includes/boost_1_60_0/boost/bind/mem_fn_template.hpp:35:36: error: invalid conversion from ‘const Foo*’ to ‘Foo*’ [-fpermissive]
         BOOST_MEM_FN_RETURN (u.*f_)();
                             ~~~~~~~^~

I'm confused about the source of the error whether it's originally from my code or the boost library. Does anyone know what the error means and how to fix it? I use g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 and boost.1.60

When binding to a member function, the first argument needs to be a pointer or a reference to the object to call the function on. It specifically can't be a value (an actual object instance). The boost::bind function have special cases for these two alternatives to generate the correct objects. It does not have any special case for passing by value.

Therefore you need to define getIntFoo as a function taking a pointer to Foo :

boost::function<int (Foo*)> getIntFoo;

Or a reference :

boost::function<int (Foo&)> getIntFoo;

You could try to use std::mem_fn to achieve the same goal:

Foo f; std::function<int(Foo &)> getIntFoo = std::mem_fn(&Foo::getIfoo); int ret = getIntFoo(f);

or if you need pointer argument, std::function could resolve this for you:

Foo f; std::function<int(Foo *)> getIntFoo = std::mem_fn(&Foo::getIfoo); int ret = getIntFoo(&f);

boost have its own alternative

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM