Search code examples
c++templatesc++17variadic-templatestemplate-argument-deduction

deduction guides for std::array


I go through the book C++ template unique quide and I try to understand how the deduction guides for std::array works. Regarding the definition of the standard the following is the declaration

template <class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;

For example if in main a array created as

std::array a{42,45,77} 

How the deduction takes place?

Thank you


Solution

  • How the deduction takes place?

    It's simple.

    Calling

    std::array a{42,45,77}
    

    match

    array(T, U...)
    

    with T = decltype(42) and U... = decltype(45), decltype(77) that is T = int and U... = int, int.

    So the type of a{42,45,47} become array<T, 1 + sizeof...(U)>, so std::array<int, 1 + sizeof...(int, int)>, so std::array<int, 1 + 2> that is std::array<int, 3>

    In other words: are extracted the types of the arguments; the first one (T) is used to give the type the array (first template parameter); the others are used just to be counted (sizeof...(U)). But, for the template second parameter, it's important to count also the first argument (of type T, so the 1 in 1 + sizeof...(U)).