hampeluzzi
hampeluzzi

Reputation: 113

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

I would like writing something like

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?

Upvotes: 2

Views: 120

Answers (1)

Jarod42
Jarod42

Reputation: 217265

You might use 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);
}

And then use it

int res = func([](int a, int b) { return a + b; } );
int res2 = func([](int a) { return a * a; } ); 

Upvotes: 3

Related Questions