0

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
user1408865
  • 136
  • 1
  • 13
  • 1
    Makes sense. `std::span` doesn't allocate to there you can have `const T`s. You probably need to write it without using `vector` if the aim is to mimic `span`. – Ted Lyngmo Aug 17 '23 at 20:15

1 Answers1

4

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);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
selbie
  • 100,020
  • 15
  • 103
  • 173
  • 2
    or just [&], since [&} will exactly only capture what you use (including this) – Pepijn Kramer Aug 17 '23 at 19:41
  • 1
    @PepijnKramer - Correct. – selbie Aug 17 '23 at 19:46
  • 3
    C++14 option: `[this](auto&& in, auto&& out){ return myFunction(in, out); };` – Ted Lyngmo Aug 17 '23 at 19:52
  • 2
    @TedLyngmo what's the difference between `(const auto& input, auto& output)` and your suggestion of `(auto&& in, auto&& out)`. Is it that the universal reference captures the `const` part for free? Or something else? – selbie Aug 17 '23 at 19:58
  • 3
    @selbie Yes, they are forwarding references, so perhaps `std::forward`ing would be more appropriate - but then the shortness of it gets lost :-) – Ted Lyngmo Aug 17 '23 at 19:58