将 lamba 隐式转换为函数 ptr 以创建类
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) {}
。
您只能有一个用户定义的转换 - 并且 lambda 到函数指针计数为用户定义。而是使用一些巫术来显式执行函数指针转换:
test2(+[](){});
另请注意,空 lambda 中的括号是可选的,因此这也有效:
test2(+[]{});
一个转化序列中只能有一个用户定义的转化。尝试:
test2(static_cast<void(*)()>([](){}));
或:
test2(static_cast<myclass>([](){}));
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 从另一个唯一 ptr 的原始 ptr 创建唯一的 ptr
- 将 lamba 隐式转换为函数 ptr 以创建类
- 使用boost lambda构造创建初始化的智能ptr的容器
- 如何创建 std::string 包装器,它将 ptr 保留为 std::string 和 ptr 到创建该包装器实例的
- ptr<Node> a = 创建对象 < 节点 > ();
- 共享Ptr与普通Ptr:声明后的对象创建