问题描述
我有一个从其他类继承的结构 A(我不允许更改)。在 A 及其方法中,我可以毫无问题地调用继承的方法(例如 A_method(int i)),但是当我尝试编写嵌套结构(例如 In)并调用 A_method(int i) 时,我有卡住了。
最初的代码看起来像这样,我无法更改它,是某种大学作业。
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
然后我尝试了这个:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
struct In {
int x;
void do_smthing() {
A_method(x);
}
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
好的,从一开始我就知道我不能这样做,因为 In 要看到它的父类,它应该有一个指向它的指针,但 In 是我代码中经常实例化的对象,我想避免传递 {{1 }} 经常到一个构造函数,所以我尝试了这种方法:
this
我想避免(如果可能的话)是这样的:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
static struct Aux
A* ptr;
Aux(A* _p) { ptr = _p; }
} aux;
struct In {
int x;
void do_smthing() {
aux.ptr->A_method(x);
}
}
virtual void play () {
//the idea is to call do_smthing() here.
}
};
RegisterPlayer(PLAYER_NAME);
这样做的主要原因是:我有更多的结构定义,它们通过其余(省略)代码被多次实例化,我不喜欢看到 struct In {
int x;
A* ptr;
In (A* _p) : ptr(_p) {}
void do_smthing() {
ptr->A_method(x);
}
}
这么多次的想法。
我不知道我是否完全遗漏了某些东西或我想做的事情,这是不可能的...如有必要,请要求澄清。
(另外,性能有点关键,我的代码将在有限的 cpu 时间下进行测试,所以我必须尽可能避免使用昂贵的方法。使用 C++11)
解决方法
您无法跳过传递 this
指针。相反,您可以在 A 中创建一个辅助函数:
template <typename InnerType,typename ...Params>
InnerType makeInner(Params&&... params)
{
return InnerType(this,std::forward<Params>(params)...);
}
然后你就可以使用
auto * a = A::factory();
auto inner = a->makeInner<A::In>();
我有一些与您的问题没有直接关系但可能会有所帮助的建议:
-
A::facotry()
返回一个std::unique_ptr<A>
而不是原始指针 - 尝试描述您要解决的问题。我有一种强烈的感觉,除了创建许多嵌套结构之外,还有更好的设计。
- 我认为传递
this
指针不会对性能产生任何影响。更重要的是确定对延迟敏感的路径并将昂贵的操作移出这些路径。