std::sort functions third parameter

Can someone explain the following code? How can the third parameter be a function with no parentheses? I understand how to use it but am a little confused by the lack of parentheses. Under what circumstances can you do this? Thanks.

1
2
3
4
5
6
7
8
bool alpha(Name x, Name y)
{
	if (x.name < y.name)
		return true;
	else
		return false;
}
  sort(array.begin(), array.end(), alpha);
http://www.cplusplus.com/reference/algorithm/sort/
comp This can either be a function pointer or a function object.

Function pointer -- a pointer to a function. You are passing an address of a function to the sort.

Parentheses indicate calling of a function.
If you put parentheses, you would be passing the result of calling the function, not the function itself. See if this part of the tutorial helps:
http://www.cplusplus.com/doc/tutorial/pointers/#pointerstofunctions
A function name with parentheses is a function call. You don't want that. You want to pass the function itself so that std::sort can use it to compare elements with.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <functional>

// using templates
template<typename T>
void callFunction1(T func)
{
	func(1);
}

// using function pointers
void callFunction2(void (*func)(int))
{
	func(2);
}

// using std::function
void callFunction3(std::function<void(int)> func)
{
	func(3);
}

void print(int i)
{
	std::cout << i << std::endl;
}

int main()
{
	callFunction1(print);
	callFunction2(print);
	callFunction3(print);
}
Topic archived. No new replies allowed.