简体   繁体   中英

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;
}

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM