Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading