C ++ lambda与捕获作为一个函数指针 [英] C++ lambda with captures as a function pointer

查看:1641
本文介绍了C ++ lambda与捕获作为一个函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩C ++ lambdas和它们对函数指针的隐式转换。我的起始示例是使用它们作为ftw函数的回调。

I was playing with C++ lambdas and their implicit conversion to function pointers. My starting example was using them as callback for the ftw function. This works as expected.

#include <ftw.h>
#include <iostream>

using namespace std;

int main()
{
    auto callback = [](const char *fpath, const struct stat *sb,
        int typeflag) -> int {
        cout << fpath << endl;
        return 0;
    };

    int ret = ftw("/etc", callback, 1);

    return ret;
}

修改为使用捕获后:

int main()
{

    vector<string> entries;

    auto callback = [&](const char *fpath, const struct stat *sb,
        int typeflag) -> int {
        entries.push_back(fpath);
        return 0;
    };

    int ret = ftw("/etc", callback, 1);

    for (auto entry : entries ) {
        cout << entry << endl;
    }

    return ret;
}

我遇到了编译错误:

error: cannot convert ‘main()::<lambda(const char*, const stat*, int)>’ to ‘__ftw_func_t {aka int (*)(const char*, const stat*, int)}’ for argument ‘2’ to ‘int ftw(const char*, __ftw_func_t, int)’

(const char *,const stat *,int)

阅读后。我了解到,使用捕获不能将隐藏转换为函数指针的lambda表达式。

After some reading. I learned that lambdas using captures can't be implicitly converted to function pointers.

有没有解决方法?事实上,他们不能隐式转换意味着他们可以显式转换? (我试过铸造,没有成功)。什么是干净的方式修改工作示例,以便我可以使用lambdas附加条目到某个对象。

Is there a workaround for this? Does the fact that they can't be "implicitly" converted mean s that they can "explicitly" converted? (I tried casting, without success). What would be a clean way to modify the working example so that I could append the entries to some object using lambdas?.

推荐答案

由于捕获lambdas需要保留一个状态,所以没有一个简单的解决方法,因为它们不是只是普通的函数。关于函数指针的一点是它指向一个单一的全局函数,并且这个信息没有空间用于状态。

Since capturing lambdas need to preserve a state, there isn't really a simple "workaround", since they are not just ordinary functions. The point about a function pointer is that it points to a single, global function, and this information has no room for a state.

最近的解决方法statefulness)是提供某种类型的全局变量,从您的lambda /函数访问。例如,你可以创建一个传统的函子对象,并给它一个静态成员函数,它引用一些唯一的(全局/静态)实例。

The closest workaround (that essentially discards the statefulness) is to provide some type of global variable which is accessed from your lambda/function. For example, you could make a traditional functor object and give it a static member function which refers to some unique (global/static) instance.

捕获lambdas的整个目的。

But that's sort of defeating the entire purpose of capturing lambdas.

这篇关于C ++ lambda与捕获作为一个函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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