Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the sum of a variadic size_t... argument in a variadic template in C++

I am trying to create an n dimensional array template class (as a wrapper for std::array or c++ arrays) in c++ that allocates a single array block for the whole n dimensional array (To avoid the overhead of using n arrays with n indexes).

In doing this I want my template to be in the following format where sizes represent the size of each dimension.

template <class Type, size_t...  sizes>
class array_dimensional{
private:
    std::array<Type, /*here is the problem, how do 
       I get the product of all the sizes?*/> allocated_array;
...

My problem is that I am not sure how to get the product of all the sizes.

Is it possible to do this, and if so how?

like image 494
yuriy206 Avatar asked Oct 16 '25 18:10

yuriy206


1 Answers

In C++14, a constexpr function may be easier to read:

template<size_t... S>
constexpr size_t multiply() {
    size_t result = 1;
    for(auto s : { S... }) result *= s;
    return result;
}

In C++17, just use a fold expression: (... * sizes).

like image 79
T.C. Avatar answered Oct 18 '25 08:10

T.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!