Is it possilbe to get a pointer to a generic lambda explicit instantiation?

Viewed 71

Is it possible to get a (member) function pointer to a specific instantiation of a generic lambda?

I know I can do so for standard non capturing lambdas, and for abbreviated templates, but I can't seem to be able to get a member function pointer for the explicitly instantiated operator() call operator member function of the invented type for the generic lambda.

#include <iostream>
 
void f1( auto v)  { std::cout << v << std::endl; }
int main() {
    void (*pf)(int) = f1<int>; // OK
    void (*pf2)(int) = [](int v)  { std::cout << v << std::endl; } ; // OK
    [](auto v) { std::cout << v << std::endl; }.operator() < int > (42); // OK
    auto generic_template = [](auto v)  { std::cout << v << std::endl; } ;
    using generic_type = decltype (generic_template);
    // void (generic_type::*pf3)(int) = &generic_type::operator()<int>;  // fails to compile

    pf(5);
}

The interest here is academic.

Edit:

As a note of interest to future readers the solutions offered to this question also apply to getting function pointers for lambdas with capture, in addition to generic lambdas. For example, based on the answers :

  auto generic_lambda = [](auto v)  { std::cout << v << std::endl; } ;
  using generic_type = decltype (generic_lambda);
  void (generic_type::*pf1)(int) const = &generic_type::operator();
  (&generic_lambda->*pf1)(43); // OK

  int x = 5;
  auto capturing_lambda = [x](int v)  { std::cout << v+x << std::endl; } ;
  using capturing_type = decltype (capturing_lambda);
  void (capturing_type::*pf2)(int) const = &capturing_type::operator();
  (&capturing_lambda->*pf2)(43); // OK
2 Answers

Yes, and you can omit the template arguments if they can be deduced from the type being initialized (or the result type of a cast) but since the lambda isn’t mutable the member function is const and so must be the pointer-to-member.

Is it possible to get a (member) function pointer to a specific instantiation of a generic lambda?

Lambda's operator() is const-qualified by default, you need to add const to the member function pointer type

void (generic_type::*pf3)(int) const = &generic_type::operator();

And since pf3 is a member function pointer, please note that it need a specific lambda object and uses .* or ->* to invoke.

(generic_template.*pf3)(42);

Demo

Related