Deduce std::array size?

C++17 std::array class template argument deduction (CTAD)

Starting with C++17, this new language feature is now used by the standard library and now allows us to omit the template types as well so that the following works:

main.cpp

#include <array>

int main() {
    std::array a{1, 2, 3};
}

instead of std::array<int, 3> a{1, 2, 3};

Tested with:

g++ -ggdb3 -O0 -std=c++17 -Wall -Wextra -pedantic -o main.out main.cpp

If we set -std=c++14 instead for example, it fails to compile with:

error: missing template arguments before ‘a’

Tested on Ubuntu 18.04, GCC 7.5.0.


Template argument deduction relies on direct type matching between actual argument and formal argument. The actual argument is an initializer list. It doesn't match the array type (at best it could match the internal raw array in a std::array, but the language rules don't support that).

Instead you can just use a raw array, to wit:

#include <stddef.h>
#include <array>

template<size_t N>
int b(int q, int const (&types)[N] )
{
    int r = q;
    for (int t : types)
    {
        r = r + t;
    }
    return r;
}

int main()
{
    b( 9, { 2, 3 } );
}

Or, if you don't absolutely need N at compile time, you can use a std::initializer_list.

There are also many other possibly relevant approaches (e.g. variadic template function, or defining an operator to build up a std::vector), but it's difficult to say what would suit your undisclosed purpose.

Tags:

C++

C++14