bod*_*ydo 5 c++ templates repeat
假设我有一个数据类型enum TreeTypes { TallTree, ShortTree, MediumTree }.
我必须根据一种特定的树类型初始化一些数据.
目前我已经写了这段代码:
int initialize(enum TreeTypes tree_type) {
if (tree_type == TallTree) {
init_tall_tree();
}
else if (tree_type == ShortTree) {
init_short_tree();
}
else if (tree_type == MediumTree) {
init_medium_tree();
}
return OK;
}
Run Code Online (Sandbox Code Playgroud)
但这是某种愚蠢的代码重复.我没有使用任何强大的C++功能,如模板.
我怎么能更好地编写这段代码?
谢谢,Boda Cydo.
小智 17
您的代码对于两个或三个值是可以的,但是您是对的,当您拥有数百个时,您需要更具工业实力的东西.两种可能的解决方
使用类层次结构,而不是枚举 - 然后您可以使用虚函数并让编译器确定要调用的实际函数
创建一个enum - > function的地图,你在启动时初始化 - 你的函数调用就变成了类似的东西 map[enum]->func()
模板在这里工作得不好,因为你试图在运行时做出决定,而模板在编译时做他们的事情.
一句话:继承
class Tree { public: virtual void initialize() = 0; }
class ShortTree : public Tree {
public:
virtual void initialize(){
/* Short Tree specific code here */
}
}
class MediumTree : public Tree {
public:
virtual void initialize(){
/* Medium Tree specific code here */
}
}
class TallTree : public Tree {
public:
virtual void initialize(){
/* Tall Tree specific code here */
}
}
Run Code Online (Sandbox Code Playgroud)
然后,无论你想在哪里调用初始化,只需确保有一个指针或多态的引用才能正常工作:
Vector<Tree*> trees;
trees.push_back(new SmallTree());
trees.push_back(new MediumTree();
trees.push_back(new TallTree();
// This will call the tree specific code for each tree in the vector
for(vector<Tree*>::iterator tree = trees.begin(); tree!=trees.end(); ++tree)
tree->initialize();
Run Code Online (Sandbox Code Playgroud)