应用场景
目前正在学习图形渲染, 封装了一个窗口类和一个渲染类,但是渲染过程需要写到窗口类的消息循环, 但是我希望他们之间能解耦,
于是想到了lamda表达式
函数指针
如果没有捕获列表的话比较简单
void test(void(*p)())
{
p();
}
int main(){
test([]()->void{
std::cout<<"我是lamda表达式参数测试"<<std::endl;
})
return 0;
}
函数模板
如果需要有捕获列表就比较麻烦了 使用函数指针将会不能匹配
错误示例
void test(void(*p)())
{
p();
}
int main(){
int count =100;
test([count]()->void{
for(int i =0 ;i<count;i++)
{
std::cout<<"我是lamda表达式参数测试,我要打印100次"<<std::endl;
}
})
return 0;
}
这个是匹配不上的
正确写法
使用模板自动匹配就是好了
template<typename T>
void test(const T& f)
{
f();
}
int main(){
int count =100;
test([count]()->void{
for(int i =0 ;i<count;i++)
{
std::cout<<"我是lamda表达式参数测试,我要打印100次"<<std::endl;
}
})
return 0;
}
如果捕获列表是对象的话需要则对象引用
class win32{
public:
void CreateWindow(){
init();
create();
show();
}
template<typename T>
void loop(const T& func){
while(!windowsclose())
{
func();
pollevent();
}
}
};
class rander{
public:
void init(){
randerInit();
}
void loop(){
rander();
}
};
int main(){
win32 app;
app.CreateWindow();
rander r;
app.loop([&r]()->void{
r.loop();
})
return 0;
}