将函数引用传递给该函数内部的结构
有一些棘手的代码,但我被困在一块上了。
我有一个从虚拟基类派生的函数。
该函数内部是一个函子。仿函数需要能够访问该函数及其父类内部的所有对象。但是,当传递对“this”或函数名称的引用时,我收到错误。
所有这些复杂性的原因是为了加快代码速度。我正在编写的算法实际上只有一个昂贵的部分。我的目的是并行化该部分。然而,该步骤通过几个步骤同时累积两个值。所以,我需要重写一些运算符。函子似乎是实现这一点的最简单方法。
任何人都可以建议如何解决这个问题。
代表代码如下:
myClassA Glm{
public:
virtual int functionA(int a, int b)=0;
}
class myClassB : public myClassA {
public:
virtual int functionA(int a, int b);
}
int functionA(int a, int b){
// do some stuff
struct MyFunctor : public binary_function<Fraction, DoubleIterator, Fraction> {
MyFunctor(myClassA& in_class, int A) : myClassA(in_class), column(iColumn) {
}
myClassA& myClassA;
int A;
Fraction operator()(double B, int A, ) {
double C = doFancyStuff(A,B);
return C;
}
}
//use stl to accumulate
accumulate(data.begin(), data.end(), temp, MyFunctor(*this, column) );
}
Have some tricky code and am stuck on a piece.
I have a function that is descended from a virtual base class.
Inside that function is a functor. The functor needs to be able to access all the objects inside of this function and its parent class. But, when passing a reference to "this" or to the function name, I get an error.
The reason for all this complication is to speed up the code. The algorithm I'm coding really only has one expensive part. My intent is to parallelize that part. However, that step accumulates over two values simultaneously, through several steps. So, I need to override some operators. A functor seemed like the easiest way to implement this.
Can anyone suggest how to solve this.
representative code below:
myClassA Glm{
public:
virtual int functionA(int a, int b)=0;
}
class myClassB : public myClassA {
public:
virtual int functionA(int a, int b);
}
int functionA(int a, int b){
// do some stuff
struct MyFunctor : public binary_function<Fraction, DoubleIterator, Fraction> {
MyFunctor(myClassA& in_class, int A) : myClassA(in_class), column(iColumn) {
}
myClassA& myClassA;
int A;
Fraction operator()(double B, int A, ) {
double C = doFancyStuff(A,B);
return C;
}
}
//use stl to accumulate
accumulate(data.begin(), data.end(), temp, MyFunctor(*this, column) );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的主要问题是过早优化。
从技术上讲,将当前的 ... 替换
为 ...
,至少
this
的问题应该消失。然后,并不是将引用作为数据成员(例如您的...)
使实例不可分配。函子对象“应该”是可分配的。因此,如果您决定继续这样做,也许最好将其替换为……
并相应地更改初始化。
干杯&呵呵,
The main problem here is premature optimization.
Technically, replace the current …
with …
and at least your problems with
this
should be gone.Then, not that placing a reference as a data member, like your …
makes instances non-assignable. And a functor object “should” be assignable. So if you decide to go on with this, perhaps better replace that with …
and change the initialization accordingly.
Cheers & hth.,