1

I'd like to specify the type of a template function as a parameter to another function.

I can almost do it like this:

template<typename T, typename U>
auto add(T left, U right) -> decltype(left + right) { return left + right; }

template<typename T, typename U>
auto subtract(T left, U right) -> decltype(left - right) { return left - right; }

void Process(??? operation) {
   ...
}

DoAdd() {
  Process(add);
  Process(subtract);
}

It feels like add and subtract could have a same type, but I'm not sure how to express that to the compiler. For example, GCC gives me this error for this code:

Is it possible to express the type of template functions (or lambdas) like this?

Josh Peterson
  • 2,299
  • 19
  • 21
  • You can also use C++20 feature called [concepts](https://en.cppreference.com/w/cpp/language/constraints) – i cant Aug 23 '22 at 10:30
  • 1
    No, they cannot have the same type because C++ standard says otherwise - each lambda expression is of unique type, no matter how similar they look. – Quimby Aug 23 '22 at 10:31
  • 1
    If you check the C++ standard library and how it handles callable objects, they use templates. Like `template void Process(F func);` – Some programmer dude Aug 23 '22 at 10:32
  • I don't agree with the duplicate. As the lambdas have `auto` arguments it isnt obvious how `std::function` helps. Simply accepting any callable is simpler and does not require to fix the argument types – 463035818_is_not_an_ai Aug 23 '22 at 10:58
  • @Quimby: they don't have to be lambdas - is there a way to do this with template functions instead? – Josh Peterson Aug 23 '22 at 11:23
  • @JoshPeterson Passing function templates around is not possible in C++ either sadly. Making `Process` a function template is the most generic option, second would be using `std::function` for `add` and `subtract`. If both lambdas won't ever capture anything, they can be implicitly casted to a function pointer but not if they are generic. – Quimby Aug 23 '22 at 11:31

0 Answers0