考虑以下抽象类AbstractEngine
:
class AbstractEngine {
static void init();
static std::string getName();
};
并考虑以下2个实现者类:
class Engine1 : public AbstractEngine {
static std::string getName();
};
class Engine2 : public AbstractEngine {
static std::string getName();
};
并且,
init()
函数应根据类的类型调用正确的getName()
:void AbstractEngine::init() {
std::cout << getName() << std::endl;
}
例如,如果我呼叫
Engine1::init()
,我希望它呼叫Engine1::getName()
而不是AbstractEngine::getName()
我怎样才能真正使
AbstractEngine::init()
调用getName()
的正确实现? 最佳答案
您可以使用CRTP,即将AbstractEngine
用作模板类,然后在继承时从AbstractEngine<EngineN>
继承:
template <typename T>
class AbstractEngine {
public:
static void init() {
std::cout << T::getName() << std::endl;
}
};
class Engine1 : public AbstractEngine<Engine1> {
public:
static std::string getName() { return "Engine1"; }
};
class Engine2 : public AbstractEngine<Engine2> {
public:
static std::string getName() { return "Engine2"; }
};
如果还需要一些动态的多态行为,则可以创建一个通用的非模板基类:
class AbstractEngine {
//I assume you would have some virtual functions here
};
template <typename T>
class AbstractEngineImpl : public AbstractEngine {
public:
static void init() {
std::cout << T::getName() << std::endl;
}
};
class Engine1 : public AbstractEngineImpl<Engine1> {
public:
static std::string getName() { return "Engine1"; }
};
class Engine2 : public AbstractEngineImpl<Engine2> {
public:
static std::string getName() { return "Engine2"; }
};