将 lambda 隐式转换为函数 ptr 以创建 class
Implicitly convert a lamba to a function ptr to create a class
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) {}
。
一个转换序列中只能有一个个用户定义的转换。尝试:
test2(static_cast<void(*)()>([](){}));
或者:
test2(static_cast<myclass>([](){}));
您只能有一个用户定义的转换 - lambda 到函数指针计数为用户定义的。而是使用一些 sorcery 来明确地进行函数指针转换:
test2(+[](){});
另请注意,nullary lambda 中的括号是可选的,因此这也有效:
test2(+[]{});
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) {}
。
一个转换序列中只能有一个个用户定义的转换。尝试:
test2(static_cast<void(*)()>([](){}));
或者:
test2(static_cast<myclass>([](){}));
您只能有一个用户定义的转换 - lambda 到函数指针计数为用户定义的。而是使用一些 sorcery 来明确地进行函数指针转换:
test2(+[](){});
另请注意,nullary lambda 中的括号是可选的,因此这也有效:
test2(+[]{});