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



我需要计算在编译时传递给模板结构的一组数字的乘积。我成功地制作了一个丑陋的解决方案:

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;
};


问题是,每次我都必须将0到模板参数馈送到我的结构中,就像一样

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


有什么变通办法可以读取最后一个零吗

注意:我是TMP的初学者。

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

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

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

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;
};

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

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;
};

一种方法是专门化空varargs。为此,您只需要主模板是可变参数:

// main template never used
template<std::size_t ...args> struct mul_all
{
};
// specialization for at least one arg
template<std::size_t n1, std::size_t ...args>
struct mul_all<n1, args...>
{
static constexpr std::size_t value = n1 * mul_all<args...>::value;
};
// specialization for empty args
template<>
struct mul_all<>
{
static constexpr std::size_t value = 1;
};

所以现在你可以做:

mul_all<1, 2, 3>::value;

C++17方法使其变得简单明了:

template <std::size_t... A>
constexpr std::size_t mul = (A * ... * std::size_t(1u));
int main() {
constexpr std::size_t val = mul<1, 2, 3, 4>;
}

对于现有的C++版本,您需要部分专门化案例mul<v>:

template <std::size_t... V>  struct mul;
template <std::size_t V> struct mul {
statuc constexpr std::size_t value = V;
};
template <std::size_t V, std::size_t... T> struct mul {
statuc constexpr std::size_t value = V * mul<T...>::value;
};
template <std::size_t... V>
using mul_v = mul<V...>::value;
int main() {
constexpr std::size_t v = mul_v<1, 2, 3, 4>;
}

最新更新