w00*_*00d 5 c++ oop polymorphism
我有一些我想要优化的代码.它看起来像这样:
function abc( string format ) {
if (format == "a") { // this is a string, I shouldn't have used single quote, sorry for the confusion
classx::a t;
doit(t);
}
if (format == "b"){
classx::b t;
doit(t);
}
if (format == "c"){
classx::c t;
doit(t)
}
if (format == "d"){
classx::d t;
doit(t);
}
}
Run Code Online (Sandbox Code Playgroud)
目前有许多不同类型的doit()函数
function doit( classx:a ) {
different code for a
}
function doit( classx:b ) {
different code for b
}
Run Code Online (Sandbox Code Playgroud)
...等等
如您所见,复制了大量代码.但是我无法弄清楚如何减少这些词.请注意:doit(x)已按不同类型重载.a,b,c,d类派生自名为"X"的类.
我可以创建一个指针类型classx :: X:
classx::X *t;
if (format == "a") t = new classx::a
if (format == "b") t = new classx::b
if (format == "c") t = new classx::c
if (format == "d") t = new classx::d
doit(*t)
Run Code Online (Sandbox Code Playgroud)
但是仍然需要为类型classx :: X编写一个doit(),带有一堆"if then"并转换为正确的类型...因为C++无法自动检测并转换为正确的类型.
我想知道是否有更快/更聪明的方法来做到这一点.提前致谢.
一种可能的方法可以减少向函数映射添加新条目的重复次数:
template<class T> void innerAbc() {
T t;
doit(t);
}
typedef std::map<std::string, void (*)()> FuncMap;
FuncMap initHandlers() {
FuncMap m;
m["a"] = &innerAbc<classx::a>;
// ... extend here
return m;
}
void abc(const std::string& format) {
static const FuncMap handlers = initHandlers();
FuncMap::const_iterator it = handlers.find(format);
if (it != handlers.end())
it->second();
}
Run Code Online (Sandbox Code Playgroud)