如何根据变量值惯用地调用 C++ 函数? [英] How to idiomatically call C++ functions based on variable value?
问题描述
假设我有一个数据类型 enum TreeTypes { TallTree, ShortTree, MediumTree }
.
Suppose I have a data type enum TreeTypes { TallTree, ShortTree, MediumTree }
.
而且我必须根据一种特定的树类型初始化一些数据.
And I have to initialize some data based on one particular tree type.
目前我已经编写了这段代码:
Currently I have written this code:
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;
}
但这是某种愚蠢的代码重复.我没有使用任何强大的 C++ 功能,例如模板.
But this is some kind of stupid code repetition. I am not using any of the powerful C++ capabilities like templates.
我怎样才能更好地编写这段代码?
How could I write this code better?
谢谢,博达·西多.
推荐答案
您的代码适用于两个或三个值,但您是对的,当您拥有数百个值时,您需要一些更具工业实力的东西.两种可能的解决方案:
Your code is OK for two or three values, but you are right, you need something more industrial strength when you have hundreds of them. Two possible solutions:
使用类层次结构,而不是枚举 - 然后您可以使用虚函数并让编译器计算出要调用的实际函数
use a class hierarchy, not enums - you can then use virtual functions and have the compiler work out which actual function to call
创建一个枚举映射 -> 函数,你在启动时初始化它 - 然后你的函数调用变成类似于 map[enum]->func()
create a map of enum -> function, which you initialise at startup - your function calls then become something like map[enum]->func()
模板在这里不能很好地工作,因为您试图在运行时做出决定,而模板在编译时做他们的事情.
Templates don't work so well here, because you are trying to make a decision at run-time, whereas templates do their stuff at compile-time.
这篇关于如何根据变量值惯用地调用 C++ 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!