它有什么方法可以将带有捕获参数的lambda存储在指针中 [英] it there any way to store lambda with captured parameters in a pointer

查看:36
本文介绍了它有什么方法可以将带有捕获参数的lambda存储在指针中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用lambda时遇到问题,我想将它们保存在指针中,但不使用常量变量来创建它们.

i have a problem with lambdas and is that i want to save them in pointers but create them using no constant variables.

// Example program
#include <iostream>
#include <string>

template<short n>
void speak(){
    std::cout << "speak:[" << n << "]" << std::endl;
}

int main()
{
    typedef void(*func)(void);

    func ptr[8];
    const short j = 10;
    
    for(short i = 0; i < 4; i++){
       ptr[i] = [=](void)->void{
            std::cout << "lamda:[" << j << "]" << std::endl;
            };
        /*ptr[i] = [=](void)->void{
            std::cout << "lamda:[" << i << "]" << std::endl;
            };*/
        ptr[i + 4] = speak<j>;
        //ptr[i + 4] = speak<i>;
    }
    
    for(short i = 0; i < 8; i++){
        ptr[i]();
    }
    
    return 0;
}

有可能用常数var"j"定义一个lambda,而没有用"i"定义一个lambda.有没有办法使用i来做到这一点,所以就没有必要这样做:

It's posible to define a lambda with a constant var "j", but no with "i". Is there any way to do it using i, so there'll be no need to do:

ptr[0] = [=](void)->void{
            std::cout << "lamda:[" << 0 << "]" << std::endl;
            };
ptr[1] = [=](void)->void{
            std::cout << "lamda:[" << 1 << "]" << std::endl;
            };
ptr[2] = [=](void)->void{
            std::cout << "lamda:[" << 2 << "]" << std::endl;
            };
ptr[3] = [=](void)->void{
            std::cout << "lamda:[" << 3 << "]" << std::endl;
            };

模板化函数是我实现它的另一种尝试,但没有成功

当我尝试使用"i"时,得到了:错误:无法转换'main()::< lambda()>'"赋值到'func {aka void()()}'""*

推荐答案

您使用 std :: function 代替了指针.只需添加标头< functional> ,然后更改

You use std::function instead of a pointer. Just include the header <functional>, and change

typedef void(*func)(void);

typedef std::function<void(void)> func;

一切都会正常!

不确定为什么()也能工作时为什么喜欢写(void).

Not sure why you like to write (void) when () works too.

之所以不能使用函数指针,是因为函数指针仅指向代码.它没有任何捕获的变量. std :: function 是一个也可以保存捕获的变量的类.

The reason you can't use a function pointer is because a function pointer just points to code; it doesn't have any captured variables. std::function is a class which is also able to hold the captured variables.

这篇关于它有什么方法可以将带有捕获参数的lambda存储在指针中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆