根据参数数量在模板中调用函数 [英] calling function in a template according to the number of paramters
本文介绍了根据参数数量在模板中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模板,该模板根据我作为参数传递的函数来计算一些值。但是,并不是我传递给模板的每个函数都需要模板中计算的所有参数。
I have a template that computes some values according to the function I pass as parameter. However, not every function I pass to the templates needs all of the parameters computed in the template.
template<typename T>
int func(T function)
{
int a = 0; // some value computed in func
int b = 10; // another value computed in func
return function(a, b);
}
int main()
{
int res = func([](int a, int b)
{
// do somthing
return 0;
}
);
return 0;
}
我想写类似
int res2 = func([](int a) // needs only parameter a
{
// do somthing
return 0;
}
);
如果函数仅需要模板传递的参数之一。
如何推断传递给模板的函数实现此功能所需的参数数量?
if the function needs only one of the parameters passed by the template. How can I deduce the number of paramters the function passed to the template needs to achieve this?
推荐答案
使用SFINAE:
template <typename F>
auto func(F f) -> decltype(f(42, 42))
{
int a = 0;
int b = 10;
return f(a, b);
}
template <typename F>
auto func(F f) -> decltype(f(42))
{
int a = 51;
return f(51);
}
然后使用它
int res = func([](int a, int b) { return a + b; } );
int res2 = func([](int a) { return a * a; } );
这篇关于根据参数数量在模板中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文