2

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?

hampeluzzi
  • 103
  • 5
  • 1
    Do you know the possible types of function parameters? I.e. are they all guaranteed to be `int`? I'm not sure it's solvable in general case, since passed function/lambda can be variadic itself. Also, you need to define how to handle functions with default parameters and such. Otherwise, you can do something like https://stackoverflow.com/questions/36797770/get-function-parameters-count and specialize/if constexpr your template from there. – Dan M. Sep 17 '18 at 14:11
  • Yes, the types of the function parameters are known, only their number varies in the two cases. – hampeluzzi Sep 17 '18 at 14:29
  • 1
    Then @Jarod42 solution should be enough for most cases (it'll be more complex if you want to cover more than a few 1,2...N args). Keep in mind, that functions with default parameters would be treated as regular functions (i.e. as if they had no defaults). – Dan M. Sep 17 '18 at 14:43

1 Answers1

3

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; } ); 
Max Langhof
  • 23,383
  • 5
  • 39
  • 72
Jarod42
  • 203,559
  • 14
  • 181
  • 302