Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the diffrence between std::greater{} and std::greater<int>()?

Tags:

c++

stl

Some people write

std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater{});

and some write like this

std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater<int>());

What is thre diffrence between std::greater{} and std::greater<int>()?

like image 929
Shipley Xie Avatar asked Dec 22 '22 15:12

Shipley Xie


2 Answers

This is new as of C++14, and this results in two completely different classes.

In C++14, std::greater acquires a default value for its template parameter: void.

You end up with either std::greater<void> or std::greater<int>.

std::greater<void> is a specialization for a so-called "transparent" comparator that deduces its parameters, see its reference for more information.

like image 92
Sam Varshavchik Avatar answered Jan 25 '23 23:01

Sam Varshavchik


std::greater<int> has an bool operator()(int const&,int const&) const that calls >.

std::greater<>, aka std::greater<void>, has a template references auto operator()(T const&, U const&) const that calls > and deduces its return value.

In c++11 and earlier, greater<void> and <> won't work.

In practice there will be no difference here. Under any non zero optimization, both versions of the comparison will be inlined.

In other contexts, the void version will let you compare dissimilar types (with suitable < or conversion overloads), and lets you neglect the type you are comparing.

The other big detail is that <void> advertises a is_transparent tag. When passed to a container like std::map, it changes some of the methods to have template arguments. This permits using a std::string key without forcing the lookup strings to become the same object type, which can save copies and allocations.

like image 45
Yakk - Adam Nevraumont Avatar answered Jan 26 '23 00:01

Yakk - Adam Nevraumont