Lambda 表达式作为类中的成员函子
当 lambda 表达式 (LE) 成为从 4.5.1 开始的 gcc 的一部分时,我感到非常兴奋,并希望他们能够提供一种方法来摆脱 C++ 中那些令人讨厌的函数指针,据我所知,这些函数指针基本上被编译为 C 函数。所有这些静态声明等...
现在我想在类中使用 LE,其中可以通过函子选择一种计算方法。但由于 C++1x 提案中的定义,这似乎根本不可能。这里是代码和问题。
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);
};
所以问题是,除非我将函子 _myOp、_minus 和 _plus 声明为静态,否则这将无法编译,但一旦我这样做,我就无法再访问成员变量(在此案例因素)。在函子定义中使用 [this] 而不是 [] 也不起作用。
老实说,恕我直言,这比函数指针替代方案更糟糕……所以我很高兴能得到帮助,但阅读新标准中的 LE 规范并没有带来太大希望。
谢谢并致以最美好的祝愿, 安迪
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现你想做什么并不完全清楚。
像这样定义 setOp 有帮助吗?
或者您可以在构造函数中分配
plus
和minus
:I find it not entirely clear what you want to do.
Would defining setOp like this help?
Or you can assign
plus
andminus
in the constructor: