Shobhit Tewari
Shobhit Tewari

Reputation: 535

Why we need to put parenthesis when giving a template type

Hello I am trying to understand this piece of code:

vector<int> a = {5, 3, 6, 1, 7};
sort(a.begin(), a.end(), greater<int>());
for(int i : a) cout << i << " "; cout << endl;

Why I need to put parenthesis after the greater. This greater is a structure defined which is like this:

/// One of the @link comparison_functors comparison functors@endlink.
  template<typename _Tp>
    struct greater : public binary_function<_Tp, _Tp, bool>
    {
      _GLIBCXX14_CONSTEXPR
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x > __y; }
    };

This is defined in stl_function.h in c++. Now I think the way it works is that I give a new type or template for this. The comparing file will make an object of this and then through operator overloading, () it will do object_name(int_value_1, int_value_2) and this returns a bool and all is understandable. But why these () when I am sending this in template. Is there some flaw in the way I think this is implemented?

PS: I said object which is a class specific term but I think in structures, it may be called that way in c++.

Upvotes: 1

Views: 613

Answers (1)

eerorika
eerorika

Reputation: 238381

Why we need to put parenthesis when giving a template type sort(a.begin(), a.end(), greater());

std::greater is a class template. std::greater<int> is an instance of that class template, and is a type (more specifically, a class type). std::greater<int>() is a temporary object (an instance of the type that is the instance of the template). The parentheses are syntax for value initialisation.

It is not possible to pass a type as an argument to a function (however, it would be possible to pass a type as a template argument to a function template). It is possible to pass a temporary object as an argument to a function.

So, we use the parentheses so that an object is created that we pass as an argument.

PS: I said object which is a class specific term but I think in structures, it may be called that way in c++.

If by structure you mean a struct: Structs are classes (that have been declared with the class-key struct).

Instances of all types are objects in C++.

Upvotes: 3

Related Questions