Chr*_*vic 7 c++ inheritance templates function-pointers
我有一个基类,它包含一个map
像这样的函数指针
typedef void (BaseClass::*event_t)();
class BaseClass {
protected:
std::map<std::string, event_t> events;
public:
// Example event
void onFoo() {
// can be added easily to the map
}
};
Run Code Online (Sandbox Code Playgroud)
处理这个工作是完美的,但现在我想创建BaseClass
一个抽象基类来源像这样:
class SpecificClass : public BaseClass {
public:
void onBar() {
// this is gonna be difficult!
}
};
Run Code Online (Sandbox Code Playgroud)
虽然我可以访问SpecificClass
我无法添加的地图,onBar
因为该event_t
类型仅定义为BaseClass
!有没有可能(可能有模板?)不会导致为event_t
我将使用的每个类定义...
(使用模板不是必需的!任何好的/合适的方法都会很好.)
更多背景资料:
这一切都是基于文本的RPG.可以调用我的基类,并且可以指定Location
任何位置,例如CivicCenter
.每个Location
对象都订阅了我EventSystem
,当我触发一个事件时,它会通知所有必要的对象.因此,我想在地图中存储一些指向私有函数的指针,这些函数以" onSetOnFire
xD"作为键的"名称"来保存动作.
经过一番思考和重新设计,我能够实现我想要的。尽管我很顽固并且仍在使用继承,但我已经重新实现了地图。现在是这样的:
class Location {
// ...
protected:
std::map<std::string, std::function<void(void)>> m_mEvents;
};
Run Code Online (Sandbox Code Playgroud)
现在我可以这样处理:
class CivicCenter : public Location {
public:
CivicCenter() {
// this is done by a macro which lookes better than this
this->m_mEvents["onTriggerSomething"] =
std::bind(&CivicCenter::onTriggerSomething, this);
}
void onTriggerSomething() {
// ...
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
通过轻松使用,std::bind
我能够实现通用函数指针。当使用类似 in 的参数时,std::function<void(int, int)>
请记住像我一样使用 boost_1
和/_2
或 lambda 表达式:
std::function<void(int,int)> f = [=](int a, int b) {
this->anotherFunctionWithParams(a, b);
};
Run Code Online (Sandbox Code Playgroud)
但这只是由于我的解决方案的完整性而指出的。
归档时间: |
|
查看次数: |
2449 次 |
最近记录: |