Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template Summing class

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;
}
like image 505
Alon Avatar asked Aug 22 '13 12:08

Alon


1 Answers

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;
};
like image 167
Dave S Avatar answered Oct 06 '22 09:10

Dave S