2

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

gilgamash
  • 862
  • 10
  • 31

1 Answers1

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); };
}
Henrik
  • 23,186
  • 6
  • 42
  • 92
  • Greetings. 'theOp' should be 'myOp', I just corrected this. The problem is the definition of the functors itself. I want to be able to let the functor used in "eval" be chosen to either be "plus" or "minus". Something like function pointer. And I want to do this using lambda expressions, as I thought this was one useful setting for them. I will give your suggestion a shot! However, it would be nicer to use functors with names instead... – gilgamash Jul 29 '11 at 10:00
  • Worked perfectly! Thanks a lot, I will just name the parameter, that will do the work. Thanks again, Andy. Sorry I can not yet vote up... – gilgamash Jul 29 '11 at 10:10