C++ lambda with captures as a function pointer

后端 未结 8 936
离开以前
离开以前 2020-11-22 15:35

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 expecte

8条回答
  •  醉话见心
    2020-11-22 15:53

    There is a hackish way to convert a capturing lambda into a function pointer, but you need to be careful when using it:

    https://codereview.stackexchange.com/questions/79612/c-ifying-a-capturing-lambda

    Your code would then look like this (warning: brain compile):

    int main()
    {
    
        vector entries;
    
        auto const callback = cify([&](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;
    }
    

提交回复
热议问题