gpt4 book ai didi

c++ - 获取指向模板化 lambda 运算符 () 的指针,无需捕获

转载 作者:行者123 更新时间:2023-12-04 12:04:15 26 4
gpt4 key购买 nike

谁能告诉我一种获取指向模板化 lamda(没有 caputes) operator () 的指针的有效方法吗?已经尝试了两种选择:

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()是成员函数指针,然而,你的fn_t的定义只是一个免费的函数指针。您应该定义您的 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>;
Demo.

关于c++ - 获取指向模板化 lambda 运算符 () 的指针,无需捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69462323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com