Home > Software engineering >  How to pass a lambda in place a reference to a functtor
How to pass a lambda in place a reference to a functtor

Time:04-21

I have a function template that takes an argument by reference

template <typename T>
void Foo(T& arg)
{
  ...
}

I want to call it passing a lambda expression, e.g.

Foo([](SomeType& nd) {nd.dosomething();  })

This does not compile (no problem though when Foo is modified to take the argument by value). What should I do to be able to pass lambda in place of a reference to a functor?

CodePudding user response:

A lambda expression is a prvalue, and won't bind to an lvalue reference.

If you change Foo to take a forwarding reference, it will be able to accept both lvalues and rvalues:

template <typename T>
void Foo(T&& arg);

CodePudding user response:

If you want to accept lvalues or rvalues, then you need to instead use a forwarding reference. That would turn your function into

template <typename T>
void Foo(T&& arg) // not an rvalue reference, but a forwarding reference
{
    ...
}
  • Related