我有一系列看起来非常相似的函数:它们采用相同的参数类型并返回字符串。
std::string f1(T arg);
std::string f2(T arg);
std::string f3(T arg);
std::string f4(T arg);
.
.
.
在循环中,它们是根据结构T中的一个变量使用的。目前,为了做到这一点,我的代码中只有一个大的switch/case
块。
有什么更好的编码风格可以做到这一点吗?这大块代码看起来很奇怪。
我希望c++能像python一样做eval("f" + str(i) + "(arg))"
区块是这样的:
std::string out = "";
switch (arg.tag){
case 1:
out += f1(arg);
break;
case 2:
out += f2(arg);
break;
.
.
.
}
对于大约20多种情况,
使用C++11,使用std::function
和映射可以很容易地做到这一点
#include <map>
#include <functional>
#include <string>
#include <iostream>
std::string f1(int) { return "f1"; }
std::string f2(int) { return "f2"; }
std::map<int, std::function<std::string(int)> > funcs = {
{1,f1},
{2,f2}
};
int main() {
std::cout << funcs[1](100) << "n";
}
如果没有C++11,您将希望使用Boost而不是std::function
,或者使用您自己的类型。你可以使用普通的旧函数指针,但这会排除一些方便的东西(如std::bind
/boost::bind
、函子对象、lambda函数
#include <map>
#include <functional>
#include <string>
#include <iostream>
std::string f1(int) { return "f1"; }
std::string f2(int) { return "f2"; }
std::map<int, std::string(*)(int)> funcs = {
std::make_pair(1,f1),
std::make_pair(2,f2)
};
int main() {
std::cout << funcs[1](100) << "n";
}
或者这个可以让你写任何你喜欢的函子对象:
#include <map>
#include <string>
#include <iostream>
struct thing {
virtual std::string operator()(int) const = 0;
};
struct f1 : thing {
std::string operator()(int) const { return "f1"; }
};
struct f2 : thing {
std::string operator()(int) const { return "f2"; }
};
// Note the leak - these never get deleted:
std::map<int, thing*> funcs = {
std::make_pair(1,new f1),
std::make_pair(2,new f2)
};
int main() {
std::cout << (*funcs[1])(100) << "n";
}
模拟Eval()
的一种方法是使用映射。映射的键将是函数的名称,值将是指向相应函数的指针。
在这种情况下,您将能够通过映射的operator[]
的名称调用所需的函数。这将以某种方式模仿eval("f" + str(i) + "(arg))"
行为,尽管它可能仍然不是适合您的最佳解决方案。