Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax for an array type?

Tags:

c++

arrays

Is it type[]? For example, could I have

T<int[]>;

for some template T.

like image 514
user383352 Avatar asked Dec 22 '22 01:12

user383352


2 Answers

The type of an "array of type T" is T [dimension], which is what you could pass as template parameters. E.g.:

someTemplate<int [10]> t; // array type as template parameter
int a[5]; // array of 5 ints named 'a'

Arrays need to have a dimension which must be greater than 0. This means that e.g. U u[]; is illegal.

There are cases that might seem like exceptions, the first being parameters:

void f(T[]);

This is a special rule for parameters and f() is actually equivalent to the following:

void f(T*);

Then there is direct inialization of arrays:

int a[] = { 1, 2, 3, 4 };

Here the array size is implicitly given through the number of elements in the initializer, thus the type of a is int[4].

There are also incomplete array types without specificied bounds, but you can't directly create instances of these (see Johannes answer for more):

template<class T> struct X { typedef T type; };
X<int[]>::type a = { 1, 2, 3 };

If you are looking for dynamic arrays, prefer standard containers like std::vector<T> instead.

like image 94
Georg Fritzsche Avatar answered Jan 12 '23 18:01

Georg Fritzsche


There are two syntaxes to denote array types. The first is the type-id syntax and is used everywhere where the language expects a compile time type, which looks like:

T[constant-expression]
T[]

This specifies an array type that, in the first form, has a number of elements given by an integer constant expression (means it has to be known at compile time). In the second form, it specifies an array type with an unknown number of elements. Similar to class types that you declare without a body, such an array type is said to be incomplete, and you cannot create arrays of that type

// not valid: what size would it have?
int a[];

You can, however, specify that type. For example you may typedef it

typedef int unknown_int_array[];

In the same manner, you may specify it as a template type argument, so the answer to your question is yes you can pass such a type specifier to a template. Notice that i talk about specifiers here, because the form you use here is not the type itself.

The second way is using the new-type-id syntax which allows denoting runtime types by having non-constant bounds

T[expression]

This allows passing variables as element count, and also allows passing a zero. In such a case, a zero element array is created. That syntax is only usable with the new operator for supporting dynamic arrays.

like image 30
Johannes Schaub - litb Avatar answered Jan 12 '23 17:01

Johannes Schaub - litb