将 lamba 隐式转换为函数 ptr 以创建类

Implicitly convert a lamba to a function ptr to create a class

本文关键字:ptr 创建 函数 lamba 转换      更新时间:2023-10-16
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 到函数指针计数为用户定义。而是使用一些巫术来显式执行函数指针转换:

test2(+[](){}); 

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

test2(+[]{}); 

一个转化序列中只能有一个用户定义的转化。尝试:

test2(static_cast<void(*)()>([](){}));

或:

test2(static_cast<myclass>([](){}));