C ++ Lambda捕获私有类成员 [英] C++ Lambda capture private class member

查看:252
本文介绍了C ++ Lambda捕获私有类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我班的一部分:

//...
        bool dump_dvars()
        {
            fstream& refvar{ output_file };

            for_each(_array_start, _array_start + *_array_size,
                [&refvar](const void* dvar) -> void
            {
                //work with output_file
            });

            return true;
        }

    private:
        void** _array_start;
        unsigned int* _array_size;
        fstream output_file;
    };

我想访问Lambda的私有成员变量output_file,该变量位于公共成员函数dump_dvars中。当我捕获this指针时,因为它是私有变量,所以我无法访问该变量,但是我也不想将其设置为公用!我已经读过这个问题(如何制作lambda类的朋友?),但我不想创建另一个函数。因此,我目前针对该问题的解决方法是创建对私有成员的引用,并将该变量通过引用捕获列表传递给我的Lambda。

I want to access the private member variable output_file of my Lambda, which is in the public member function dump_dvars. When I capture the this pointer I can not access the variable because it is private, I also don't want to make it public though! I already read this question (How to make the lambda a friend of a class?) but I don't want to create another function. So my current fix for the problem is creating a reference to the private member and pass that variable via reference capture list to my Lambda.

这是一个好的解决方案和好的样式还是有更好的解决方案?

Is that a good solution and good style or is there a better solution?

推荐答案

您应该在lambda中捕获 this。

You should capture 'this' in the lambda.

下面的代码可以与g ++,clang,VS2010和VS2013一起编译并正常工作。

The following code compiles and works just fine with g++, clang, VS2010 and VS2013.

#include <iostream>

class A
{
public:
    A() : x(5){}
    void f() const
    {
        ([this]()
        {
            std::cout << x << std::endl;
        })();
    }
private:
    int x;
};

int main()
{
    A a;
    a.f();
}

这篇关于C ++ Lambda捕获私有类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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