Lambda with explicit object parameter and std::invoke_result_t

176 Views Asked by At

How do I get the return type of a lambda that has a deducing this signature using std::invoke_result_t.

auto lambda = [](this auto& self, int x) -> int {
    return x;
};  
  
auto x = std::invoke_result_t<decltype(lambda), int>{}; //won't compile

Do I need to somehow specify the self argument inside the std::invoke_result_t ?

I've tried without "deducing this" and the above sample works.

Edit: compiler explorer link

1

There are 1 best solutions below

0
康桓瑋 On BEST ANSWER

In your lambda, this auto& self actually takes an lvalue reference to this, but std::invoke_result_t<decltype(lambda), int> invokes the rvalue lambda.

Since the rvalue cannot be bound to the lvalue reference, invoke_result has no valid member type, just as std::move(lambda)(0) is ill-formed.

You should invoke the lambda with an lvalue, e.g.

auto x = std::invoke_result_t<decltype(lambda)&, int>{};

Or make the lambda accept a forward reference to this

auto lambda = [](this auto&& self, int x) -> int {
    return x;
};