我有一个当前的代码工作很好。我想让它的一部分更有效率。C++通过函数指针来模板函数
我有一堂课,Foo
,和一大堆Foo
的子类做不同的事情(在这个例子中,我使用Bar
作为唯一的子类)。
我定义在它的构造,宣布了一系列step
是我的主要程序的每个循环迭代中Bar
“更新”如何。这很酷,因为我可以添加多个step
,每个运行迭代次数不同。
问题是,将一个step
添加到Bar
的过程是多余的,我想让它变得更少。
这里是我的类声明如下所示:
template <class T>
class Step {
public:
Step();
void (T::*fnPtr)(); // function to execute when step is run within a Foo
int count; // number of iterations to execute on
}
class Foo {
public:
Foo();
void doSomething();
template <class T>
void addStep(Step<T>* newStep) {
// adds a new step to a linked list
}
}
class Bar : public Foo {
public:
Bar();
void doAnotherThing();
void doYetAnotherThing();
void omgAnotherThing();
}
我Bar
构造会是这个样子:
Bar::Bar() {
// ah four lines of code (at least!) every time I want to add a step!
Step<Bar>* a = new Step<Bar>;
a->fnPtr = &Bar::doAnotherThing;
a->count = 10;
addStep(a);
Step<Bar>* b = new Step<Bar>;
b->fnPtr = &Bar::doYetAnotherThing;
b->count = 20;
addStep(b);
Step<Bar>* c = new Step<Bar>;
c->fnPtr = &Bar::omgAnotherThing;
c->count = 6;
addStep(c);
}
理想情况下,我想了Bar
的一步创作的样子有点像这个:
Bar::Bar() {
// very nice! I like!
addANewStep(&Bar::doAnotherThing,10);
addANewStep(&Bar::doYetAnotherThing,20);
addANewStep(&Bar::omgAnotherThing,30);
}
但我不是很确定,特别是如何将&Bar::doAnotherThing
传递给函数。
有什么建议吗?
最简单的办法取代
Step<T>
,到目前为止。非常好。 –@RyanTuck:真的!向Step添加构造函数。它应该做什么开始。 –