有效地将参数包的大小提高到某个索引
Efficiently get the size of a parameter pack up to a certain index
我希望能够确定参数包子集中从 0 到给定索引的字节数。
现在我正在使用一种非 constexpr 的方式来做到这一点。 下面是我的代码:
template <size_t index, typename... args> struct pack_size_index;
template <size_t index, typename type_t, typename... args>
struct pack_size_index <index, type_t, args...> {
static const size_t index_v = index;
static const size_t value(void) {
if (index_v > 0) {
return sizeof(type_t) + pack_size_index<index - 1, args...>::value();
}
return 0;
}
};
template <size_t index> struct pack_size_index <index> {
static const size_t index_v = index;
static const size_t value(void) { return 0; }
};
用法:
//output: 5 (equal to 1 + 4)
std::cout << pack_size_index<2, bool, float, int, double>::value() << std::endl;
//output: 20 (equal to 8 + 8 + 4)
std::cout << pack_size_index<3, double, double, float, int>::value() << std::endl;
这样可以完成工作,但这使用运行时比较,并且每当使用此方法时,生成的可执行文件的大小都会迅速增加。 有什么更便宜的方法可以做到这一点?
解决了,我认为:
template <size_t index, typename... args> struct pack_size_index;
template <size_t index, typename type_t, typename... args>
struct pack_size_index <index, type_t, args...> {
static const size_t value = (index > 0)?
(sizeof(type_t) + pack_size_index<index - 1, args...>::value):0;
};
template <size_t index> struct pack_size_index <index> {
static const size_t value = 0;
};
相关文章:
- 在索引和值类型上参数化的惯用向量类型
- 在运行时C++11 个索引模板参数包,以便访问第 N 种类型
- 如何获取参数包中元素的索引
- std::ios_base::register_callback 的索引参数有什么作用?
- 使用查找表选择具有运行时索引的可变参数类型
- 从 1 中创建新的字符 * 作为参数,元素位于 2 个索引之间
- 从常量字符*参数中取出索引
- 如何使用函数参数中的int指针来获取2d数组中最大值的索引并返回指针
- 通过const函数中的参数索引返回std :: map的值
- 在gldrawelements中,索引参数的含义是什么
- 如何在可变参数模板中使用索引
- 有效地将参数包的大小提高到某个索引
- 根据给定的索引集获取参数包的子集
- 可变参数模板类,从其参数列表中获取特定类型的索引
- 将 char 数组作为参数传递时,为什么索引中不包含 null 终止符?
- 带有1个参数的C++2D数组索引(为什么这样做?)
- 通过带有数组索引的类传递参数
- 获取索引时qmodelindex的父参数
- 指针和数组上操作符[]的索引参数类型
- 使用Variadic模板解压缩参数列表时获取参数索引