如何从字符串参数调用函数 [英] How to call functions from string parameter

查看:68
本文介绍了如何从字符串参数调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它的参数为char *或string,我的问题是如何使用给定的字符串参数调用相应的函数而不使用字符串比较方法。如果我们使用如下的switch-case语句,这是有效的: br $> b $ b

I have a function which has it's arguments as char* or string,My problem is how to call a respective function using given string parameter without using string comparison methods.Is is efficient if we use switch-case statements as below:

#include<string>
#include<iostream>
void foo(){ cout<<"foo";}

void bar(){cout<<"bar";}

void func_exe(string& s){

// I want to use this string parameter "s"/char* and execute respective function,without maps or string comparison,I want to use switch case  

}
void main(){

func_exe("foo");
func_exe("bar");

}





谢谢



thank you

推荐答案

几个选项:



1.在输入字符串上有一个if级联来调用相应的函数

(伪代码)

couple of options :

1. have a if cascade on the input string to call the appropriate function
(pseudo-code)
if ( s == "foo" )
  foo();
else if ( s == "bar" )
  bar();
else
  cout<< "unsupported function";





2.有一个函数指针映射(?)键入string并调用相应的函数。 (我没有导出函数指针,所以没有伪代码)



我确定还有其他方法可以做到这一点。



祝你好运。

Max。



2. have an map of function pointers (?) keyed to the "string" and call the appropriate function. (I'm no export on function pointers, so no pseudo-code )

I'm certain there are other ways to do it.

Good luck.
Max.


整个想法完全没用。考虑一下定义函数 func_exec 时获得的值。想象一下,它已经完美运行,无需参数即可调用任何函数而无需任何支持。它是否会为您的代码添加任何值,此外还可以直接调用 foo bar 或其他任何内容。



不会。它实际上是一个纯粹的负面贡献,也就是说,与你不喜欢的情况相比,它会让你的代码变得更糟没有这个功能。调用 bar() 将始终更好然后 func_exec(bar)。总是,没有排除。好多了。您不能输入错误的函数,因为编译器会指出您的错误。但不是在bar中,你可以以任何方式拼错。



毫无意义,永远。



-SA
The whole idea is totally useless. Think about the value you gain when you define the function func_exec. Imagine that it already works perfectly and can call any function without parameters without any need for support. Will it add any value to your code, in addition to the possibility to call foo, bar or anything else directly.

No. It will actually be a purely negative contribution, that is, it will make your code worse compared to the situation when you don't have this function. The call bar() will always be better then func_exec("bar"). Always, no exclusions. Much, much better. You cannot mistype the function, as the compiler will point out your error. But not in "bar", which you can misspell in any way.

Makes no sense, ever.

—SA


如果你想使用切换案例'然后你必须将字符串映射到一个整数,可能创建穷人 - 哈希函数,最终你会模仿使用 std :: unordered_map 。我的建议是:直接出于此目的使用 std :: unordered_map
If you 'want to use the switch case' then you have to map the string to an integer, possibly creating the poor-man-hash-function, eventually you would mimic using a std::unordered_map. My advice is: directly use the std::unordered_map for the purpose.


这篇关于如何从字符串参数调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆