Search code examples
c++templatestemplate-meta-programmingvariadic

template Metaprogramming: multiplying a bunch of template arguments


I need to compute the product of a bunch of numbers at compile time passed to a templated struct. I succeeded to make an ugly solution :

template<std::size_t n1, std::size_t ...args>
struct mul_all
{
    static constexpr std::size_t value = n1 * mul_all<args...>;
};
template<>
struct mul_all<0>
{
    static constexpr std::size_t value = 1;
};


The problem is that each time I have to feed 0 to template args to my struct like so

int main()
{
    std::cout <<  mul_all<1,2,5,4,5,7,0>::value << " " 
              <<  mul_all<4,2,0>::value;
    return 0;
}


is there any workaround to get read of that last zero?

note: I am a beginner in TMP.


Solution

  • In C++17, with folding expression, you may directly do

    template<std::size_t ...args>
    struct mul_all
    {
        static constexpr std::size_t value = (args * ...);
    };
    

    Before, you have to do the partial specialization:

    template<std::size_t n1, std::size_t ...args>
    struct mul_all
    {
        static constexpr std::size_t value = n1 * mul_all<args...>::value;
    };
    
    template<std::size_t n>
    struct mul_all<n>
    {
        static constexpr std::size_t value = n;
    };