Search code examples
c++templatesvariadic-templatesstdarray

Multiplication of Template Arguments


I have the following problem:

template< size_t... N_i >
class A
{
  // ...
  std::array< float, /* product of the unpacked elements of N_i */ > arr;
};

As you can see above, I try to declare an std::array named arr as a member of a class A. Here, I want arr to have the size product of the unpacked elements of N_i, e.g., in case of A<2,3,4>, "arr" should have the size 2*3*4=24.
Does anyone know how this can be implemented?


Solution

  • In C++17:

    std::array < float, (... * N_i)> arr;
    

    In C++14:

    // outside the class
    template<size_t... Ns>
    constexpr size_t product(){
        size_t p = 1;
        for(auto n : { Ns... }) p *= n;
        return p;
    }
    
    // then
    std::array< float, product<N_i...>()> arr;
    

    In C++11:

    template<size_t... N_i>
    struct product { 
        static const size_t value = 1; 
    };
    
    template<size_t N_1, size_t... N_i>
    struct product<N_1, N_i...> {
        static const size_t value = N_1 * product<N_i...>::value;
    };
    
    std::array< float, product<N_i...>::value> arr;
    

    Alternatively, you can use a recursive constexpr function.