在C++中获取可变参数模板中的可变参数size_t ...参数的总和

yur*_*206 3 c++ arrays templates variadic-templates

我试图std::array在c ++中创建一个n维数组模板类(作为c ++数组的包装器),为整个n维数组分配一个数组块(避免使用n个数组和n个索引的开销).

在这样做时,我希望我的模板采用以下格式,sizes表示每个维度的大小.

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;
...
Run Code Online (Sandbox Code Playgroud)

我的问题是我不知道如何获得所有尺寸的产品.

有可能这样做,如果是这样的话怎么样?

T.C*_*.C. 6

在C++ 14中,constexpr函数可能更容易阅读:

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

在C++ 17中,只需使用fold表达式:(... * sizes).