Search code examples
c++c++14template-argument-deductionstdarrayfunction-templates

How do you deduce the size of a std::array?


In the following code:

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

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

How can I avoid having to specify 2 in the call to b for N? Why can't this type be automatically deduced? Without it I get the error:

'b': no matching overloaded function found 'int b(int,const std::array<int,N> &)': could not deduce template argument for 'N'


Solution

  • 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.