从同一个父函数调用不同的子函数
我希望有一个像这样的公共父函数,
void main (param 1, param 2)
{
<stuff to do>
param1();
print("The function %s was called", param 2);
<more stuff to do>
}
其中 param 1 将是要调用的函数的名称,param 2 将是一些描述性文本。 param 2 很简单,我已经解决了这个问题,但我不清楚如何通过传入函数名称来从同一父函数调用函数。 父函数还有一些其他功能,但不是拥有多个仅在其调用的函数上有所不同的父函数或具有 switch 语句的单个父函数,如果这种方式可能的话,我更喜欢这种方式。 有什么想法吗?
Im looking to have a common parent function like so
void main (param 1, param 2)
{
<stuff to do>
param1();
print("The function %s was called", param 2);
<more stuff to do>
}
Where param 1 will be the name of the function to be called and param 2 will be some descriptive text. param 2 is easy and I have that solved, but Im unclear as to how I would call a function from the same parent function by passing in the functions name. THere are a few other things that the parent function does, but instead of having multiple parent function who only differ in the function they call or a single parent with a switch statement, id prefer if this way was possible. Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您实际上想要传递给参数 1 的是指向您要调用的函数的函数指针,而不是该函数的名称。
看看这个关于函数指针的教程。
What you actually want to pass for param 1 is a function pointer to the function you would like to call, as opposed to that function's name.
Have a look at this tutorial about function pointers.
这是什么语言? 如果函数不是这种语言的一等公民,你就不能这样做。
如果它是像Java这样的东西,你可以通过传入一个实现接口的对象来解决这个问题,然后只在该对象上调用该函数。
What language is this? if functions aren't first-class citizens in this language, you can't do it
If it's something like Java, you could get around this by passing in an object that implements an interface, and just call that function on the object.
我想说函数指针是一件好事,但你也许可以利用预处理器来做你想做的事......(学习如何使用函数指针是一件好事)......
我的意思是,如果param2 是静态已知的东西,拥有函数指针是毫无用处的。如果您有动态值,并且在运行程序时一旦您想要给出 param2 = foo 然后 param2 = bar...,函数指针会更好
...你实际上需要不同的函数原型,或者你可以有类似的东西......
并且总是具有相同的主体但在命令行上给出不同的 -D ...
I'd say that function pointers are a good thing but you may be able to leverage the pre-processor to do what you want...(learning how to use function pointers is a good thing though)...
I mean, if param2 is something that is known statically, it's pretty useless to have function pointers.. Function pointers would be better if you've dynamic values and while running your program once you want to give param2 = foo and then param2 = bar...
Do you actually need different function prototypes or could you have something like...
and always have the same body but giving different -D on the command line...
像这样的东西吗?
Something like this?
一般来说,这在 C 语言和编译语言中并不容易做到。
在 Windows 上,我有这样的东西(已经很长时间了):
如果您愿意手动将 args 推入堆栈,则实际的函数调用签名可以更灵活。
This is not easy to do in C and compiled languages in general.
On Windows I have something like this ( its been a long time ):
The actual function call signature can be more flexible, if you are willing to manually push args onto the stack.