c++ - 根据参数个数调用模板中的函数

标签 c++ c++11 templates

我有一个模板,它根据我作为参数传递的函数计算一些值。但是,并非我传递给模板的每个函数都需要模板中计算的所有参数。

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++ - 根据参数个数调用模板中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52369598/

相关文章:

c++ - Const 限定符和前向引用

c++ - 考虑引用和 const 的可变参数函数包装器

c++ - 是否可以从同一线程移动分配 std::thread 对象

c++ - 使用模板和/或 constexpr 在编译时构建函数

c++ - 模板模板参数和 clang

c++ - 如何处理不良 SDK

c++ - typeid 的成本是多少?

c++ - 重载决议中的默认参数 v 模板优先级

c++ - 带有尾随返回类型的 final、override、const 的语法

c++ - lambda 闭包中的模板