【问题标题】:calling function in a template according to the number of paramters根据参数数量在模板中调用函数
【发布时间】:2018-09-17 22:18:48
【问题描述】:

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

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;
}
);

如果函数只需要模板传递的参数之一。 如何推断传递给模板的函数需要多少参数来实现这一点?

【问题讨论】:

  • 你知道函数参数的可能类型吗? IE。他们都保证是int吗?我不确定它在一般情况下是否可以解决,因为传递的函数/lambda本身可以是可变参数。此外,您需要定义如何处理具有默认参数等的函数。否则,您可以执行 stackoverflow.com/questions/36797770/… 之类的操作,然后从那里专门化/if constexpr 您的模板。
  • 是的,函数参数的类型是已知的,只是它们的数量在两种情况下有所不同。
  • 那么@Jarod42 解决方案对于大多数情况应该足够了(如果你想覆盖多个 1,2...N 参数,它会更复杂)。请记住,具有默认参数的函数将被视为常规函数(即,就好像它们没有默认值一样)。

标签: c++ c++11 templates


【解决方案1】:

您可能会使用 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; } ); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多