Trying to play around with variadic template but for some reason my brain has gone numb.
I am trying to create a class to sum up variables in compilation time, but cannot create the stopping condition correctly.. I tried to it like this:.. but it does not compile, quick 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;
}
You need to declare a base template first. You've only really declared the two specializations 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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With