我想简化以下代码:
switch (index)
{
case 1:
output = function1();
break;
case 2:
output = function2();
break;
case 3:
output = function3();
break;
....
其中index
是编译时常量。
如果我使用预编译器宏,则需要使用它n
次,其中n
是事例数。如何将上述代码简化为 O(1) 行代码?
试试这个(假设函数 1-n 是真实名称。 正如你所说,该索引是一个编译时常量):
#define CALLFUNCTION(x) function##x()
output = CALLFUNCTION(1);
更正:这不适用于变量,如果直接使用常量,这将起作用。如果提供的代码是每个 case 语句中的全部内容,这可能会破坏目的。
根本不需要做开关。或者,您可以使用模板专用化。
template<int index> function();
output = function<index>();
并为每个索引专用化函数模板。
template<> function<1>(){return 1;} // or {return function1();}
如果它不是编译时常量,则需要像 Fomin Arseniy 建议的那样生成开关。另一种选择是使用函数指针数组
你不能用宏来做到这一点 - 但这将起作用(我认为):
int (*functions[])() = { &function1, &function2, &function3};
int output = functions[index]();
可能是超宏可以稍微简化你的工作。只需使用代码创建"counter.def"文件:
COUNTER(1)
COUNTER(2)
COUNTER(3)
#undef COUNTER
然后在任何情况下使用开关或任何其他具有重复计数的结构
switch(index)
{
#define COUNTER(i) case i: output = function##i(); break;
#include "counter.def"
}
派对迟到了,从那时起,检查它的提升库很有用:
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#define DECL(z, n, _) case n: (function ## n)(); break;
BOOST_PP_REPEAT_FROM_TO(1, 3, DECL, _)
但是,如果您使用的是较新的C++,建议改用模板元编程和if constexpr ()
。