是否可以获取指向泛型 lambda 的特定实例的(成员)函数指针?
我知道我可以对标准非捕获 lambda 和缩写模板执行此操作,但我似乎无法获取发明类型的显式实例化的operator()调用运算符成员函数的成员函数指针对于通用 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);
}
这里的兴趣是学术性的。
编辑:
作为 future 读者感兴趣的注释,除了通用 lambda 之外,针对此问题提供的解决方案也适用于通过捕获获取 lambda 的函数指针。例如,根据答案:
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
最佳答案
是的,如果可以从正在初始化的类型(或强制转换的结果类型)推导出模板参数,则可以省略模板参数,但由于 lambda 不是可变
,因此成员函数是const
因此必须是指向成员的指针。
关于c++ - 是否有可能获得指向通用 lambda 显式实例化的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70704551/