Lambda expression as member functors in a class
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 开发者_JAVA技巧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
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); };
}
精彩评论