set class template / Compare?

Hello, I am reading a STL book, and going over a section about sets to learn more about them. Ive not been dedicated to learning c++ for very long so still very much a beginner so there is still a lot of noobish stuff i dont know. So when I came across the class template for set there was a few things i was confused with, and hoping someone could help with it.

Firstly, I have only ever used typename, for simple class templates, like <typename T> so the other typenames in this code has confused me a bit. What is Compare in this? I have tried looking this up and have found nothing apart from how to compare things. Is this just like a variable name that is set equal to less<T> (I have found something for 'less', which i found really interesting. I have been finding a whole bunch of classes that i didnt even know existed that do a whole bunch of different stuff).

I am thinking that maybe, like I said above, compare is like a variable name, so later on in the template, the keyword compare can be used. Is this right?
And the same for Allocator, I learnt that allocator is a class that is used for creating/destroying etc. So would Allocator just be a name that is used to refer to the allocator?

Maybe my issue with understanding this falls with not fully understanding the keyword typename. Can I just imagine replacing typename with an int, double etc, or in this case a type less or allocator?


1
2
3
4
5
  namespace std {
template <typename T,
typename Compare = less<T>,
typename Allocator = allocator<T> >
class set;
Last edited on
'Compare' is a type template parameter, same as T. What the declaration is saying is that, if the template instantiation only specifies the first template parameter, Compare should default to less<T>.
So, for example, set<int> is equivalent to set<int, less<int>, allocator<int>>. You also the option of specifying some other type, so set<int, Foo> would be the same type as set<int, Foo, allocator<int>>.
https://en.cppreference.com/w/cpp/keyword/typename
typename can be used as an alternative to class


Lets say that you write a template and then use it:
1
2
3
template <class T> class X;

X<int> sample;

We know that T is name of type and in your use T is int.
It is somewhat less intuitive to refer to primitive type, like int, as a class rather than as a typename.

Both this site's reference and cppreference describe set with:
1
2
3
4
5
template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;


If one would like to emphasize the type of types, then one would write:
1
2
3
4
5
template<
    typename Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

This would hint to human reader that Compare and Allocator cannot be primitive types.
Last edited on
Topic archived. No new replies allowed.