Variadic Summing class template

Trying to play with a variation pattern, but for some reason my brain was numb.

I am trying to create a class for summing variables at compile time, but I cannot correctly create a stop condition. I tried to do it as follows: .. but it does not compile, does it help anyone?

#include <iostream> #include <type_traits> using namespace std; template<size_t Head, size_t ...Rest> struct Sum { static const size_t value = Head + Sum<Rest...>::value; static void Print() { cout << value; } }; template<> struct Sum { static const size_t value = 0; }; int _tmain(int argc, _TCHAR* argv[]) { Sum<5,5,5>::Print(); return 0; } 
+6
source share
1 answer

First you need to declare the base template first. You just announced two specializations that you would use.

 template<size_t...> struct Sum; template<size_t Head, size_t ...Rest> struct Sum<Head, Rest...> { static const size_t value = Head + Sum<Rest...>::value; static void Print() { cout << value; } }; template<> struct Sum<> { static const size_t value = 0; }; 
+7
source

Source: https://habr.com/ru/post/952282/


All Articles