0

Predicate arguments in C++ STL algorithms are defined to be type arguments in template. Form what I understand, predicates can be either of two things -

1) A structure with an overload of operator() returning bool. This can be used as a type in template argument for predicate.

2) A function returning bool. How is this a type parameter for predicate in template?

  • 1
    Let us reverse the question - what do *you* see wrong with function being a type? A function is simply converted to a *function pointer* which will point to it – Fureeish Sep 15 '18 at 23:57
  • I'm pretty sure predicates are normal value arguments. – melpomene Sep 16 '18 at 00:06
  • @CássioRenan `template< class InputIt, class OutputIt, class UnaryPredicate > OutputIt copy_if( InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred );` The predicate is `pred`, which is a normal value argument. Its type is generic (a template parameter, `UnaryPredicate`), but the predicate itself is a normal value (either a function pointer or an instance of a class). – melpomene Sep 16 '18 at 00:11
  • @melpomene class keyword in template is another name for typename, which is nothing but a type parameter and not a value parameter. – Abhishek Tripathi Sep 16 '18 at 00:13
  • @AbhishekTripathi Dude, what. The predicate is `pred`, not `UnaryPredicate`. `UnaryPredicate` is just the name of the type of `pred`. – melpomene Sep 16 '18 at 00:18
  • @melpomene Gotchu, my bad. Sorry. So, its nothing but either a class instance or a pointer to a function, which in this case is pointer to some type. – Abhishek Tripathi Sep 16 '18 at 00:22
  • @CássioRenan I mean neither of those. I mean *not a template parameter*, as in it's part of the normal function parameter list `(...)`, not the template parameter list `template< ... >`. – melpomene Sep 16 '18 at 00:24

1 Answers1

2

Let's inspect a simple definition:

template <typename T>
struct TD;

bool is_odd(const int x) {
    return x % 2 != 0;
}

template<typename T>
void foo(T arg){
    TD<T> type_displayer;
}

int main() {
    foo(is_odd);
}

When you run this code, you get an error. An error saying that:

'TD<bool (*)(int)> type_displayer' has incomplete type

That's my favourite 'hack' to inspect the deduced type (T from foos argument). You can clearly see how I passed a function to foo in main, but the deduced type was <bool (*)(int)>, which is a pointer to a function that returns bool and takes an int as argument.

That's all it is to passing a function as an argument to a template function.

For references on function pointers, see this question and this tutorial.

Fureeish
  • 12,533
  • 4
  • 32
  • 62