Search code examples
c++c++20variadic-templatestemplate-meta-programming

C++ Sum parameter pack into a template argument


How can I sum all the std::size_t parameters passed through the template into one std::size_t value that will define the size of the array.

template<typename T, std::size_t... N>
class Example {
    std::array<T, N + ...> data; // std::array<T, sum of all N...>
};

Solution

  • You almost have it. You need to use a fold expression for this which is the same syntax, just surrounded with (). That gives you

    template<typename T, std::size_t... N>
    struct Example {
        std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
    };
    

    And in this example you'll get an error that tells you the array member has the size of the sum of the parameters.

    template<typename T, std::size_t... N>
    struct Example {
        std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
    };
    
    template <typename T>
    struct get_type;
    
    int main() 
    {
        Example<int, 1, 2, 3> ex;
        get_type<decltype(ex.data)>{};
    }
    

    Error:

    main.cpp: In function 'int main()':
    main.cpp:27:33: error: invalid use of incomplete type 'struct get_type<std::array<int, 6> >'
       27 |     get_type<decltype(ex.data)>{};
          |                                 ^
    main.cpp:22:8: note: declaration of 'struct get_type<std::array<int, 6> >'
       22 | struct get_type;                                             ^
          |        ^~~~~~~~                                              |
                                  // here you see 1 + 2 + 3 == 6 --------+
    

    live example