[英]How to pass functions with different signatures as parameter to other function
I'm struggling with the following problem and if this has been asked, I apologize.我正在努力解决以下问题,如果有人问过这个问题,我深表歉意。
I have multiple parts in my code doing a similar job - they mainly differ in a function call:我的代码中有多个部分在做类似的工作 - 它们主要在 function 调用中有所不同:
int doSomething(string* s, int i) {
...
}
int doSomethingOther(string* s, string t) {
...
}
int main() {
int num;
string s;
// do something with num
// repeating part start
string str1;
// do some stuff
int res1 = doSomething(&str1, num);
cout << "res: " << res1 << " str1: " << str1 << endl;
// end
// do something with s
// here we go again but with a different function call
string str2;
// do some stuff
int res2 = doSomethingOther(&str2, s);
cout << "res: " << res2 << " str2: " << str2 << endl;
//end
return 0;
}
Is it possible to define a general function to reduce the writing effort?是否可以定义一个通用的 function 以减少编写工作? One possibilityis using a parameter for this common function indicating which function should be used.
一种可能性是为这个常见的 function 使用一个参数,指示应该使用哪个 function。 On the other hand if the called function was always the same, it would be also possible by using a function pointer:
另一方面,如果调用的 function 始终相同,则也可以使用 function 指针:
...
void generalFct(int p, int(*doSomethingFct)(string* aString, int anInt)) {
string s;
// do some stuff
int res = (*doSomethingFct)(&s, p);
cout << "res: " << res << " s: " << s << endl;
// do some other stuff
}
...
int main() {
int num;
// do something with num
generalFct(num, &doSomething);
...
// update num...
generalFct(num, &doSomething);
}
But unfortunately the signature of doSomething
and doSomethingOther
differs (otherwise that would be a solution) and that's where I stuck.但不幸的是
doSomething
和doSomethingOther
的签名不同(否则这将是一个解决方案),这就是我坚持的地方。 Is there any kind of technique that helps me to achieve my goal, ie something like that:是否有任何技术可以帮助我实现目标,例如:
int main() {
int num;
// do something with num
generalFct(num, &doSomething);
...
// update num...
generalFct(num, &doSomethingOther);
}
You can do it like this:你可以这样做:
#include <iostream>
#include <functional>
#include <string>
// std::function&& so it can accept temporaries
// std::function<int(void)> ensures you can only use
// functions returning an int.
int generic_function(int p, std::function<int(void)>&& fn)
{
auto value = fn();
auto result = (p * p) + value;
std::cout << result << "\n";
return result;
}
int doSomething(const std::string& str, int i)
{
std::cout << "doSomething\n";
return i;
}
int doSomethingOther(const std::string& str1, const std::string& str2)
{
std::cout << "doSomethingOther\n";
return 12;
}
int main()
{
// pass a lambda
generic_function(42, [] { return doSomething("1", 1); });
generic_function(12, [] { return doSomethingOther("1", "2"); });
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.