Question

Say I am writing a library that should provide some default computing (function), but enables the user to provide his own, at compile-time. For instance, say the library provides a function that returns his argument times 3, but the user can provide his own function.

Consider the following program (to be seen as a MWE):

float myFunction( float v )  // the function the user needs
{
    return v*2;
}

int main()
{
    FuncWrapper f;
    cout << "default: " << f(2) << endl; // should print "6"

    f.AssignFunction( myFunction );
    cout << "now is: " << f(2) << endl; // should print "4"
}

So I have build a functor FuncWrapper that wraps a std::function, as proposed also here:

struct FuncWrapper
{
    std::function<float(float)> foo; // the function used

    float def( float v ) // the default behaviour member function definition
    {
        return v*3;
    }

    float operator()( float v ) // call of function
    {
        return foo(v);
    }

    void AssignFunction( float (*uf)(float) ) { foo = uf; }

// constructor: initializes to default function
    FuncWrapper() : foo(&FuncWrapper::def) {}
};

On my machine (gcc 4.6.3) with -std=c++0x, I get non human-readable error messages, as stated in this other answer. For conveniency, the code is runnable here. Seems to be gcc 4.8, and it doesn't like the constructor (among other errors...):

main.cpp: In constructor 'FuncWrapper::FuncWrapper()':
main.cpp:27:64: error: no matching function for call to 'std::function<float(float)>::function(float (FuncWrapper::*)(float))'

Why is this assignment illegal ? I have searched for this topic, maybe wrong keyword, but didn't find anything relevant.

Any clue? Or a simpler solution, maybe without std::function but with a function pointer?

Était-ce utile?

La solution

In your example code, you try to assign your member function to a std::function with signature float(float). These two are not compatible, since the member function has a different calling convention: it requires a this argument.

Make your default function static to avoid this.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top