模板元编程:将一堆模板参数相乘

che*_*jar 6 c++ templates variadic template-meta-programming

我需要在传递给模板化结构的编译时计算一堆数字的乘积.我成功地做出了一个丑陋的解决方案:

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


问题是,每次我必须将0模板args提供给我的结构,就像这样

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


是否有任何解决方法来读取最后一个零?

注意:我是TMP的初学者.

Jar*_*d42 6

在C++ 17中,使用折叠表达式,您可以直接执行

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

以前,你必须做部分专业化:

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


saj*_*oie 5

您需要将您的专业化替换为:

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