Jack
Jack

Reputation: 65

What is this template syntax and unsigned type?

I'm new to C++ and I am have difficulty understanding this code:

template <typename T = unsigned>
  1. What is T = unsigned means?
  2. Does the compiler enforce the unsigned on the given type?

Upvotes: 1

Views: 95

Answers (2)

Niall
Niall

Reputation: 30605

The template has a default parameter for the type T, in this case unsigned int.

The unsigned is short hand for unsigned int.

For example; in client code if the template was a class template, then an object could be declared with or without explicitly adding a type to the declaration;

ABC<> abc1; // the <> is required
ABC<unsigned int> abc2; // equivalent type to abc1
ABC<float> abc3;

Related question, regarding the syntax.

Upvotes: 1

acwaters
acwaters

Reputation: 586

That's a default template parameter; it is similar to a default function parameter. If you don't put in an argument, it will default to unsigned [int]. So imagine this:

template <typename T = unsigned>
struct foo
{
    T one;
    T two;
};

If I declare for example a foo<char>, the resulting structure will have two char members. But the default parameter lets me declare a foo<>, and that structure will have two unsigned int members, because unsigned int is the default.

Upvotes: 6

Related Questions