Lambda expression as member functors in a class

烂漫一生 提交于 2019-12-24 00:35:08

问题


I was thrilled when lambda expressions (LE) were part of the gcc starting a 4.5.1 and hoped they would grant a way of getting rid of those nasty functions pointer in C++, which were basically, to my understanding, compiled as C functions. All those static declarations etc...

Now I wanted to use LEs in a class, where one can choose a method of computation by a functor. But due to the definition in the proposal for C++1x, this seems not to be possible at all. Here the code and the problem(s).

testLE.h

#include<functional>
typedef std::function<double(double, double)> tMyOp;
class testLE
{
  public:
  testLE(){ m_oFactor = 2.5; }
  void setOp(const int i)
  {
    if (i > 0) {myOp = plus;} else {myOp = minus;}
  }
  double eval(double x, double y) { return myOp(x, y); }

private:
  double m_oFactor;
  tMyOp plus;
  tMyOp minus;
  tMyOp myOp;
};

testLE.cpp

#include "testLE.h

tMyOp testLE::plus = [](double x, double y) -> double
{
  return m_oFactor*(x + y);
};

tMyOp testLE::minus = [](double x, double y) -> double
{
  return m_oFactor*(x - y);
};

So the problem is, that this will not compile unless I declare the functors _myOp, _minus and _plus as static, but as soon as I do this, I have no access any longer to the member variables (in this case factor). And using [this] instead of [] in the functors' definition does not work either.

Honestly, imho this is worse than the function pointer alternative.... So I would be very glad about help, but reading the specs for LEs in the new standard does not give much hope.

Thanks and best wishes, Andy


回答1:


I find it not entirely clear what you want to do.

Would defining setOp like this help?

void testLE::setOp(int i)
{
    if (i > 0) 
        myOp = [this](double x, double y) -> double { return m_oFactor*(x + y); };
    else
        myOp = [this](double x, double y) -> double { return m_oFactor*(x - y); };
}

Or you can assign plus and minus in the constructor:

testLE()::testLE()
{
    m_oFactor = 2.5;
    plus = [this](double x, double y) -> double { return m_oFactor*(x + y); };
    minus = [this](double x, double y) -> double { return m_oFactor*(x - y); };
}


来源:https://stackoverflow.com/questions/6871179/lambda-expression-as-member-functors-in-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!