Avery3R
Avery3R

Reputation: 3190

Why must we do template <class/typename> T instead of just template T

Instead of

template <typename T>
void func(T arg) {/* something */}

why can't we do

template <T>
void func(T arg) {/* something */}

From cplusplus.com :

The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way.

It just seems like unnecessary boilerplate to me.

Upvotes: 9

Views: 566

Answers (2)

Justin Aquadro
Justin Aquadro

Reputation: 2310

http://www.cplusplus.com/doc/tutorial/templates/ See the section on Non-type parameters for templates.

You need some keyword to distinguish type-parameters from non-type parameters.

template <class T, int N>
class mysequence {
    T memblock [N];
  public:
    void setmember (int x, T value);
    T getmember (int x);
};

Upvotes: 11

John Zwinck
John Zwinck

Reputation: 249203

Because template arguments are not always types. You can have a template argument that is an integral value, for example, as in the case of std::bitset<size_t N>.

Upvotes: 9

Related Questions