如何在参数包中找到最大值? [英] How to find maximum value in parameter pack?

查看:76
本文介绍了如何在参数包中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个问题的例子:常量变量的模板应根据参数扩展其类型。尽管直接方法是可行的,但通过提供类型或基础类型名的大小,则容易出错。

Here is an example of problem: a constant variable's template should expand its type based on parameters. While direct way is possible, by giving size of type, or underlying typename, it's error-prone.

#include <iostream>

template<size_t bit>
constexpr const uint16_t BIT = 1 << bit;

template<size_t... bits>
constexpr const uint16_t BITS = (uint16_t(1 << bits)|...);

int main()
{
    std::cout << BITS<0,1,3,12> << std::endl;
}

想法是实现模板数据类型,该类型将返回类型,它是无符号整数,至少应为参数包中最大值的大小。

Idea is to implement template data type which would return type which is unsigned integer at least of size of greatest value in parameter pack. This also would allow to check if template arguments are sane.

推荐答案

在C ++ 17中相当简单。我们可以通过简单调用 std :: max 自C ++ 14起,初始化列表的重载为 constexpr )。

Pretty straight forward in C++17. The maximum value we can calculate with a simple invocation of std::max (the initializer list overload is constexpr since C++14).

我们需要将结果插入到将大小映射为整数类型的实用程序中,但是现在编写起来相当简单:

The result we'll need to plug into a utility that maps sizes to integer types, but that's fairly simple to write now:

template<std::size_t N>
struct size2Type {
    static auto type_calculator() {
        static_assert( N < 64 );
        if constexpr ( N < 8 )
            return uint8_t{};
        else if constexpr ( N < 16 )
            return uint16_t{};
        else if constexpr ( N < 32 )
            return uint32_t{};
        else
            return uint64_t{};
    }

    using type = decltype(type_calculator());
};

然后,将其用于您的原始示例:

Then, putting it to use in your original example:

template<size_t bit>
constexpr typename size2Type<bit>::type BIT = (typename size2Type<bit>::type)(1) << bit;

template<size_t... bits>
constexpr typename size2Type<std::max({std::size_t(0), bits...})>::type BITS = (BIT<bits> | ... | 0);

我没有美化演员表,但是也可以编写一个实用程序来实现这一目标。

I didn't prettify the cast, but a utility can be written to accomplish that too.

您可以实时查看

这篇关于如何在参数包中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆