c ++ 11 lambda函数对象成员

tha*_*sis 2 lambda c++11

我正在为一些科学计算编写一个抽象类的C++库.在其中一个类中,我使用的是一个函数对象,以便我可以将它作为数值算法中的参数传递.我必须这样做,因为通常计算需要额外的参数,我无法在数值算法中传递.我使用私有类(嵌套类)成功实现了代码,用于构造函数对象.我现在正在尝试使用lambdas重写类来创建函数对象,但我不确定如何限制对lambdas中特定成员变量的访问.

我有一个简单的程序来说明我面临的问题.

#include <iostream>
#include <functional>
using namespace std;

class A
{
public:
    A(int inI, int inJ) : _i(inI), _j(inJ)
    {
        create_functor();
    }

    A(const A& rtSide) : _i(rtSide._i),_j(rtSide._j)
    {
        create_functor();
    }

    A(A&& rtSide) : _i(rtSide._i), _j(rtSide._j)
    {
        rtSide.f = nullptr;
        create_functor();
    }

    A& operator=(A&& rtSide)
    {

        _i = rtSide._i;
        _j = rtSide._j;
        create_functor();

        rtSide.f = nullptr;

        return *this;
    }

    A& operator=(A& rtSide)
    {
        if (this == &rtSide)
            return *this;

        _i = rtSide._i;
        _j = rtSide._j;
        create_functor();

        rtSide.f = nullptr;

        return *this;
    }

    ~A() {}

    void reset_i(const int& newI) { _i = newI; }

    function<double(const double&)> f;

private:
    void create_functor()
    {
        f = [this](const double& inX) -> double {return inX * static_cast<double>(_i); };
    }

    int _i;
    int _j;
};

int main()
{

    A _A1(2,0);
    A _A2(1,0);

    _A2 = _A1;

    cout << _A2.f(2) << endl;

    _A2.reset_i(4);

    cout << _A2.f(2) << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然上面的代码工作正常,但我无法弄清楚如何仅限于成员变量_i限制对外部作用域的访问.

任何想法/建议将不胜感激.

Pio*_*cki 5

在C++ 11中,您可以std::reference_wrapper<T>按值使用和捕获该包装:

std::reference_wrapper<decltype(_i)> r = _i;
f = [r](const double& inX) -> double {return inX * static_cast<double>(r.get()); };
Run Code Online (Sandbox Code Playgroud)

或其较短的等价物:

auto r = std::ref(_i);
f = [r](const double& inX) -> double {return inX * static_cast<double>(r.get()); };
Run Code Online (Sandbox Code Playgroud)

演示1

在C++ 14中,您可以使用通用的lambda捕获表达式:

f = [&_i = _i](const double& inX) -> double {return inX * static_cast<double>(_i); };
Run Code Online (Sandbox Code Playgroud)

演示2