2

Could I get clarification on the below C++ code. It creates a function template of a function called gSequence. I'm trying to understand the return type dyn_vector.

Is dyn_vector just the start STL vector renamed?

template <class T>
using dync_vector = std::vector<T>;

template <class T_data>
dyn_vector<T_data> gSequence(size_type dataSize)
{
    dyn_vector<T_data> result(dataSize);

    return result;

}

1 Answers1

4

It is not a redefinition. As @n.m. suggests, it is a (templated) type alias, sort of.

First, let's forget about templates. Suppose I'm giving an exam and I use int values for students' grades. I could write:

typedef int grade_t;

after which I would use grade_t for variables or parameters which treat something as an exam grade. Now, a compiler would just have those functions take an int, but when we read the code we'll have a better idea of what's meant. Also, this will help us if we want to change the grade type (e.g. allow fractional grade values).

Ok, that was a type alias - which is very basic stuff that you may already be aware of. What about that using business then? Well, it's the same thing... that is to say, the statement:

using grade_t = int;

has exactly the same meaning as the typedef statement I listed above. It is a more modern syntax in C++ (adopted in 2011).

Now the templates come back into the picture. std::vector is a class template (and therefore a type template), not a type in itself. It has two parameters which, when set, give us a concrete type:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

the second template parameter gets a default value if we specify nothing else. Now, a dyn_vector is also a template, but with only one parameter, i.e. it's like std::vector but absolutely guaranteed to only use the default allocator. This is why I qualified the first sentence above with a "sort of".

Bernardo Sulzbach
  • 1,216
  • 12
  • 23
einpoklum
  • 86,754
  • 39
  • 223
  • 453