template元编程:将一堆模板参数相乘
template Metaprogramming: multiplying a bunch of template arguments
我需要计算在编译时传递给模板结构的一组数字的乘积。我成功地制作了一个丑陋的解决方案:
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>;
}
相关文章:
- 如何使用结构和指针推动和弹出一堆双打
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 当我在结构中包含多个数组时,我的程序会跳过一堆代码
- 在共享指针的值中调用 std::swap 调用一堆构造函数和析构函数
- 使用带有.lib和一堆.dll和.h文件的Python CFFI
- 用 c++ 编写一堆类似的 if 语句的漂亮方法
- 当我尝试编译程序时,我遇到了一堆错误,例如:'std::max':找不到匹配的重载函数
- Swig C++ to python:编译一堆.cpp和.h文件
- template元编程:将一堆模板参数相乘
- 串联模板参数包,用于一单位参数
- 在.NET中存储一堆恒定值的最佳方法
- 我的一堆函数出现"undefined reference"错误,我不知道为什么
- 制作一堆 int 数组
- 为什么glut.h会在CodeBlocks中弹出一堆未定义的引用
- 更换一堆std ::矢量条目
- 在Windows下编译程序会给出一堆"error: template with C linkage"报告
- C++将字符从静态数组复制到动态数组会添加一堆随机元素
- 如何创建一堆多维数组
- 如何在Linux中使用Makefile一次编译一堆测试C++文件
- 如何在一堆数字中找到一个不同的值