根据参数的数量调用模板中的函数
calling function in a template according to the number of paramters
>我有一个模板,可以根据我作为参数传递的函数计算一些值。但是,并非我传递给模板的每个函数都需要模板中计算的所有参数。
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;
}
);
如果函数只需要模板传递的参数之一。 如何推断传递给模板的函数实现此目的所需的参数数量?
你可以使用 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; } );
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销