有效地将参数包的大小提高到某个索引

Efficiently get the size of a parameter pack up to a certain index

本文关键字:索引 参数 有效地      更新时间:2023-10-16

我希望能够确定参数包子集中从 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;
};