[英]Get a pointer to a templated lambda operator () without captures
谁能告诉我一种有效的方法来获取指向模板化的 lamda(无头)运算符 () 的指针? 已经尝试了两种选择:
int main()
{
static
auto l = []<bool a, bool b>( unsigned c ) -> unsigned
{
return (unsigned)a + b + c;
};
using fn_t = unsigned (*)( unsigned );
fn_t fnA = &l.operator ()<true, false>; // doesn't work
fn_t fnB = &decltype(l)::operator ()<true, false>; // also doesn't work
}
铿锵声(-cl)12:
x.cpp(9,13): error: cannot create a non-constant pointer to member function
fn_t fnA = &l.operator ()<true, false> ; // doesn't work
^~~~~~~~~~~~~~~~~~~~~~~~~~~
x.cpp(10,14): error: address of overloaded function 'operator()' does not match required type
'unsigned int (unsigned int)'
fn_t fnB = &decltype(l)::operator ()<true, false> ; // also doesn't work
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
x.cpp(4,11): note: candidate function template has different qualifiers (expected unqualified but found 'const')
auto l = []<bool a, bool b>(unsigned c) -> unsigned
^
MSVC 2019 最新更新:
x.cpp(9): error C2276: '&': illegal operation on bound member function expression
x.cpp(10): error C2440: 'initializing': cannot convert from 'overloaded-function' to 'fn_t'
x.cpp(10): note: None of the functions with this name in scope match the target type
lambda 的operator()
的地址类型是成员 function 指针,但是,您的fn_t
的定义只是一个空闲的 function 指针。 您应该将fn_t
定义为:
using fn_t = unsigned int (decltype(l)::*)(unsigned int) const;
然后以下应该工作:
fn_t fnA = &decltype(l)::operator ()<true, false>;
或者,为什么不呢?
auto fnB = &decltype(l)::operator ()<true, false>;
它是 lambda 在某些情况下(此处不存在)可以转换为 function 指针,而不是其成员operator()
。 并且您不能将成员指针转换为 function 指针。
一种解决方法是使用另一个 lambda。
fn_t fn = [](unsigned c) { return decltype(l){}.operator()<true, false>(c); };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.