Henry Maathuis
Henry Maathuis

Reputation: 123

Extract and manipulate template arguments in C++

I'm trying to implement a template which can return the sum of its template arguments. The number of template arguments varies so therefor I would like to make a variadic template accepting a parameter pack. I was able to make a function template which can do the following:

Sum(1,2,3)

But I also want to be able to do something like:

Sum<1,2,3>())

Can someone explain how I can extract these templates arguments and store the sum of those arguments in something like a struct?

Thanks already!

Upvotes: 0

Views: 437

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

You can use variadic templates, template specialization, and compile-time recursion.

// Forward-declaration of a `Sum` variadic template class
// that takes some integers as template parameters
template<int...> 
struct Sum;

// Case 0: variadic template pack is not empty 
// (match one integer `TX` and any remaining integers `TXs...`)
// (`TXs...` can be empty)
template<int TX, int... TXs> 
struct Sum<TX, TXs...> 
    : std::integral_constant<int, TX + Sum<TXs...>::value>
{

};

// Case 1: variadic template pack is empty
template<>
struct Sum<> 
    : std::integral_constant<int, 0>
{

};

int main()
{
    assert(Sum<1, 2, 3>::value == 6);
}

Also, if you have an already-working constexpr function getSum(...), you can wrap it with a struct:

template<int... TXs> 
struct Sum
{
    constexpr static int value{getSum(TXs...)};
};

Upvotes: 5

Related Questions