0

I don't understand why the following code compile and works:

template<typename Predicate> 
void foo(Predicate p) {      
}

bool g(int n) {     
}

void user(int n) { 
    foo(g); 
}

foo is supposed to get a function object that will run on a data structure but I made the method simpler, because what I don't understand is how can this works? A method isn't an object. The normal way to do it is to create a new class, override operator() and then send an instance of that class.

2
  • If this is on gcc/clang, stick a std::cout << __PRETTY_FUNCTION__ << '\n'; in foo and see what p really is. See it live. Commented Jul 22, 2014 at 10:55
  • A number of the standard library algorithms are dependent on this being possible, e.g. std::for_each and std::copy_if Commented Jul 22, 2014 at 11:11

2 Answers 2

4

Well, in this case the Predicate parameter is substituted by a function pointer of type bool (*func) (int). Nothing wrong with that...

Sign up to request clarification or add additional context in comments.

Comments

3

The Predicate template argument can be almost any type. So you can use it for function pointers and classes as well as the basic types.

If you use the function argument p as a function, then it can be anything that is callable, like a function pointer, an object whose class have an operator() member function, a pointer to a static member function, a std::bind object, a std::function object or a lambda expression.

It can't be a pointer to a member function though, because to call a pointer to a member function you need an instance to call it on. For this use std::bind.

2 Comments

"Any type" isn't really true. Function parameters may not have function or array type.
This doesn't answer why it works. Also, Predicate is a (type) template argument, so instantiating the template will make Predicate a type, not an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.