假设一个函数func1
的参数是一个函数f
及其参数。假设有两个函数func2
和func3
,应该使用以下定义传递给func1
:
bool func2(int a, int b, float c){
// does something with arguments and returns the boolean result
}
bool func3(int a, int b, float c, float d){
// does something with arguments and returns the boolean result
}
我想知道应该如何定义
func1
,使其与这两个函数兼容。当然有一个解决方法,那就是将一个虚拟参数传递给func2
,但这不是一个好的解决方案。我已阅读this post,但它似乎不是兼容的解决方案。有任何想法吗?编辑:
该函数是一个C++模板,它等效于python函数,例如:
def func1(f, int a, int b, *args):
if f(a, b, *args):
# does something
最佳答案
可变参数模板可以为您提供帮助。最简单的版本:
template<class Fn, typename... Ts>
void func1(Fn fn, int a, int b, Ts... args) {
if (fn(a, b, args...))
...
}
func1(func2, 1, 2, 3);
func1(func3, 1, 2, 3, 4);
关于c++ - 将具有不同数量参数的函数传递给另一个函数C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58777002/