C++ - Is it possible to instantiate a `vector` without specifying the type?

No, std::vector is a template and cannot be instantiated without specifying the template parameters.


Templates in general

Ignoring the details of std::vector for the moment, it is possible to define a default type for a template parameter of a class template. For example:

template <class T = int>
class foo { 
    T *bar;
};

In such a case, you don't have to specify a type to instantiate that template. At the same time, you do have to include a template parameter list. The trick is that the list can be empty, so you could instantiate this template in any of the following ways:

foo<long> a; // instantiate over long. The `int` default is just ignored
foo<int>  b; // instantiate over int. Still doesn't use default
foo<>     c; // also instantiates over int

std::vector specifically

std::vector does use a default parameter for the type of the allocator, but does not provide a default for the type being stored, so the definition looks something like this:

template <class T, class allocator = std::allocator<T>>
class vector
// ...

So, if you don't specify otherwise, the allocator type for the vector will be an std::allocator instantiated over the same type as you're storing--but you do always have to specify a type you're storing, because no default is provided for that type.

Summary

It is definitely possible to specify defaults for all the parameters to a template, in which case it's possible to instantiate the template without (explicitly) specifying the type at the instantiation--but std::vector has one template parameter for which no default is provided, so to instantiate vector, you must specify a type for that parameter.


C++17 does support instantiation of vectors without type. Please see this article, https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

for more information.

So, for instance writing this will work:

vector v {1, 2, 3};  // instead of vector<int>

if you compile with this "-std=c++17" flag.

Tags:

C++

Stl

Vector