Search code examples
c++lambdac++17

Replace boost::bind with lambda


I would like to replace a boost::bind with a lambda. Can you please advise on how to go about doing this?

I have a function declared as

bool myFunction(const vector<double>& input, vector<double>& output) const
{
    ...
}
...
...
boost::bind<bool>(std::mem_fn(&classname::myFunction), this, _1, _2) // Replace with lambda

Solution

  • I get an error trying to declare vector<const double>.

    The C++ Standard forbids containers of const elements because allocator is ill-formed.'

    Confirmed here

    So let's assume you can change the signature of myFunction to be:

    bool myFunction(const vector<double>& input, vector<double>& output)
    {
        return false;
    }
    

    To set:

    auto fn = [this](const vector<double>& input, vector<double>& output) {
        return myFunction(input, output);
    };
    

    Or if you need to save fn off as a member variable:

    std::function<bool(const vector<double>&, vector<double>&)> fn =
        [this](const vector<double>& input, vector<double>& output) {
            return myFunction(input, output);
        };
    

    To invoke:

    fn(inputVector, outputVector);