[英]How to call a function based on the input value?
Lets say I want to only call one function in my code: func(), but depending on which value I give it, have it go STRAIGHT to the correct 'version' of that function? 可以说我只想在我的代码中调用一个函数:func(),但是根据我给它的值,它是否可以直接到达该函数的正确“版本”?
I know this would be possible to do with if-statements/switch-statements, but then it would have to (inefficiently) check which value was passed. 我知道这可以与if语句/ switch语句一起使用,但随后必须(效率低下)检查传递了哪个值。 I was hoping there's a pre-compiled way to do it?
我希望有一种预编译的方法?
Is something like this possible to do in an efficient way? 这样的事情有可能有效地做到吗?
func(3)
Will execute the third version of func() 将执行func()的第三个版本
func[1]{
cout "One";
}
func[2]{
cout "Two";
}
func[3]{
cout "Three";
}
You could have an array of function pointers: 您可能有一个函数指针数组:
int foo_1() {
cout << "One";
}
// ...
auto[] functions = {foo_1, foo_2, foo_3};
and call it with 并用
functions[0]();
Actually, case-switch is very efficient, because even if you have a very large number of targets, it can compile this in the code as a table of jumps, rather than as a chain of ifs - so all parts of the switch will be an equal amount of instructions away. 实际上,case-switch非常有效,因为即使您有很多目标,它也可以在代码中作为跳转表而不是ifs链进行编译-因此,switch的所有部分都是等量的指令。
http://en.wikipedia.org/wiki/Switch_statement#Compilation http://en.wikipedia.org/wiki/Switch_statement#Compilation
If the range of input values is identifiably 'small' and has only a few gaps, some compilers that incorporate an optimizer may actually implement the switch statement as a branch table or an array of indexed function pointers instead of a lengthy series of conditional instructions.* This allows the switch statement to determine instantly what branch to execute without having to go through a list of comparisons.
如果输入值的范围可以确定地是“很小的”并且只有几个空隙,那么一些包含优化器的编译器实际上可以将switch语句实现为分支表或索引函数指针数组,而不是冗长的条件指令序列。 *这样,switch语句可以立即确定要执行的分支,而不必通过比较列表。
Furthermore: 此外:
1) Don't worry about premature optimization if you haven't identified the code as a bottleneck that's slowing your program down. 1)如果您没有将代码识别为使程序变慢的瓶颈,请不要担心过早的优化。
2) Why does calling a function with different values make it do entirely different things? 2)为什么调用具有不同值的函数会使它执行完全不同的事情? Shouldn't it be different functions, instead?
它不是应该具有不同的功能吗? (If you want to call a bunch of functions in a loop, you could always create an array of function pointers - look up function pointers)
(如果要在循环中调用一堆函数,则始终可以创建一个函数指针数组-查找函数指针)
When you do func(3)
, where the argument(s) are constant, the compiler will automatically optimize the function if it has no side effects. 当您执行
func(3)
,如果参数是常量,则编译器将在没有副作用的情况下自动优化该函数。 This means the function may not modify a global variable, member variable, or write to any pointers passed to the function. 这意味着该函数不得修改全局变量,成员变量或写入传递给该函数的任何指针。 The
if
statements will disappear at runtime. if
语句将在运行时消失。
I believe it could be possible to use a templated function for this. 我相信可以为此使用模板化函数。
Eg 例如
template< int subfunc>
void func< subfunc>();
void func<1>();
Something like this should work :) 这样的事情应该工作:)
That way when you call it you say: func<1>();
这样一来,您就可以说:
func<1>();
and it will call the other function. 它将调用另一个函数。
Just checked it. 刚刚检查。 This solution will not work as the user wishes since the entered value in the chevrons must be a constant/compile-time resolved value.
由于人字形中输入的值必须是恒定/编译时解析的值,因此该解决方案将无法按用户期望的方式工作。
Since we're tough men using C++ here, I would use a map
from string
(your input) to void *
(represents all the functions), and this way I won't need to count on any specific order of my callable functions in the map. 由于我们硬汉使用C ++在这里,我会用一个
map
从string
(你的输入) void *
(代表所有的功能),这样一来我就不用在我的调用函数的具体顺序指望地图。 I also don't need to convert the input to a number (in case the input is from the console and it's a string) 我也不需要将输入转换为数字(以防输入来自控制台且是字符串)
#include <map>
#include <string>
#include <iostream> // for cout
using namespace std; // that's the way I like it
int main()
{
map<string, void *> funcs;
funcs["func1"] = (void *)func1;
funcs["func2"] = (void *)func2;
...
string s = myinput();
if (funcs.find(s) != funcs.end()) {
((void (*)())funcs[s])(); // call the function (first casting it to the function's data type
}
else cout << "### Error: function " << s << " doesn't exist in map" << endl;
return 0;
}
You can do it with value templates. 您可以使用值模板来做到这一点。 But if you're doing that, why have a function at all?
但是,如果要这样做,为什么还要有功能呢? And why not just have N differently named functions, it will be FAR less confusing when maintaining your code.
并且为什么不仅仅拥有N个命名不同的函数,还可以在维护代码时减少混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.