5

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

6
  • I'm playing around with meta-programming a bit. I've tried passing std::invoke_result_t<decltype(lambda), decltype(lambda)&, int>{}; and similar. It didn't work for me. Commented Sep 5, 2023 at 7:29
  • Your std::invoke_result_t<decltype(lambda), decltype(lambda)&, int>{}; seems to work; EDIT but maybe because without __cpp_explicit_this_parameter Commented Sep 5, 2023 at 7:42
  • Your snippet works in MSVC latest (which has full support for C++23): godbolt.org/z/McGbGKzdY, but doesn't in any other compiler (i.e. GCC godbolt.org/z/3ox9roc14). I would say it is still an unsupported feature... Commented Sep 5, 2023 at 8:13
  • 1
    Sorry, my bad. Your snippet works with a slight modification to the this parameter. It works without the reference marker Commented Sep 5, 2023 at 8:15
  • But passing by reference (I think) is an error. this must be passed either by value (pointer copy) or as a forwarding reference. See devblogs.microsoft.com/cppblog/cpp23-deducing-this. Both work fine Commented Sep 5, 2023 at 8:18

1 Answer 1

7

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.