How to typedef array for different sizes

Question | Sep 26, 2019 | nextptr 

The std::array is an excellent choice for most of the cases, because it has the size() and the empty() properties and does not decay to a pointer. But there are conditions where we have to work with regular arrays.

In a hypothetical situation, suppose we have to create some char[] identifiers of different lengths, and we have created typedef synonyms of those identifiers:

typedef char identifier1_t[6];
typedef char identifier2_t[12];

Now we can use those identifier synonyms to pass them as array references to functions. The advantage of passing arrays by reference is that we can use the sizeof() operator and a range-based for loop to iterate over them. Here is an example:

// get identifier1_t as const&
void foo(const identifier1_t& id) {
 std::cout << sizeof(id) << "\n"; // 6
 // range-based loop
 for(auto c : id)
    std::cout << c << "\n";

To manage those aliases better, we want to create an alias template, identifier_t<Size>, such that the synonyms for different length identifiers can be created using that template as follows:

typedef identifier_t<6> identifier1_t;
typedef identifier_t<12> identifier2_t;
 // OR with C++11 alias-declaration
using identifier1_t = identifier_t<6>;
using identifier2_t = identifier_t<12>;

Consider the following two implementations of the identifier alias template identifier_t<Size> - one with the typedef and the other utilizing the new C++11 alias-declaration:


template<size_t S>
typedef char identifier_t[S];


template<size_t S>
using identifier_t = char[S];

Select the implementation from above that is valid - the one that compiles and runs as expected - below (please check for the Explanations for details):

2015 nextptr