Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why c++ template parameters should be declared as class type?

Syntax of Function Template

template <**class** T, ...>
    returntype functionname(arguments)
    {
           .....
           .....
     }

I have two Questions?

  1. Why the template parameter should be declared as a class type?(ie with the use of class keyword)
  2. When we declared it as a class type then what the thing the compiler will do?
like image 546
Mei Avatar asked Dec 06 '22 15:12

Mei


1 Answers

That's the usual confusion that arises from the usage of class in template arguments.

That class thing has nothing to do with classes; it merely says that the template accepts a type template argument (as opposed to integral1 template arguments), which can be any type, not only classes.

So, why did they choose class? Because they had to use a keyword that was surely not used in any C++ program and more or less "sounded good" - and class was ok, since it was already a reserved keyword in C++.

Notice that there's an alternative to class: the typename keyword. They are perfectly equivalent2, but typename in my opinion is much more clear, since the name just says "what follows is a type argument", without making you think that it must be a class.

Why both syntax are allowed? Because the typename keyword had do be introduced in the language later (when they noticed that it was necessary to add another keyword to disambiguate some declarations inside templates); then, it was "retrofitted" also for the template arguments declarations. This usage of the class keyword was kept for compatibility with programs/documentation written in the meantime.


  1. here I say "integral" for simplicity, obviously I mean non-type template parameters in general (C++11, §14.1 ¶4).
  2. There is no semantic difference between class and typename in a template-parameter.

    (C++11, §14.1 ¶2)

like image 153
Matteo Italia Avatar answered Mar 16 '23 09:03

Matteo Italia