gpt4 book ai didi

c++ - 将 lambda 隐式转换为函数 ptr 以创建类

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:23 24 4
gpt4 key购买 nike

struct myclass
{
myclass(void(*)()) {}
};

void test1(void(*)()) {}
void test2(myclass) { }
void cb() {}

int main()
{
test1(cb); // works
test2(cb); // works
test1([](){}); // works

test2([](){}); // does not work, why? there's no "explicit" keyword next to myclass.

}

为什么这不起作用?

以下显然有效,但我不想使用它。

     test2(myclass([]{}));

注意:我不想接受 std::function<void()>>而且我不想创建 template<T> myclass(T f) {}要么。

最佳答案

您只能有一个用户定义的转换 - 并且 lambda 到函数指针计数为用户定义的。而是使用一些 sorcery明确地进行函数指针转换:

test2(+[](){}); 

另请注意,nullary lambda 中的括号是可选的,因此这也有效:

test2(+[]{}); 

关于c++ - 将 lambda 隐式转换为函数 ptr 以创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218906/

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