c++ - 根据参数数量在模板中调用函数
问题描述
我有一个模板,它根据我作为参数传递的函数计算一些值。但是,并非我传递给模板的每个函数都需要模板中计算的所有参数。
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; } );
推荐阅读
- google-bigquery - BigQuery 中的枚举或常量?
- inheritance - 向继承的 Odoo 模型添加序列字段时遇到问题
- archlinux - 添加一个 makepkg dlagent,它接受非零退出代码
- c++ - 使用 FSCTL_MOVE_FILE 重新分配文件集群太慢
- ruby-on-rails - Puma 发现了这个错误:nil:NilClass (NoMethodError) 的未定义方法 `first'
- php - 使用 Xdebug 跟踪时出现持续错误
- flutter - 如何在显示另一个小部件之前显示一段时间?
- spring-boot - Spring jaeger 将跨度传播到异步方法
- javascript - 试图从对象数组中获取 id 并将这些 id 推送到数组中
- java - 如果玩家键入 /launch,如何让我的代码向玩家返回“无效号码”消息
或 /launch 字符串