如何在编译时找出integer_sequence是否包含给定的数字?

问题描述 投票:4回答:2

鉴于:

typedef std::integer_sequence<int, 0,4,7> allowed_args_t;

和:

template<int arg> void foo()
{
    static_assert( /*fire if arg not in allowed_args_t!*/ )
}

我应该如何编写static_assert在编译时尽可能便宜?

我正在使用C ++ 17。

c++ c++17 variadic-templates
2个回答
13
投票

您可能想要使用:

template <int ... Is>
constexpr bool is_in(int i, std::integer_sequence<int, Is...>)
{
    return ((i == Is) || ...);
}


typedef std::integer_sequence<int, 0, 4, 7> allowed_args_t;


template<int arg> void foo()
{
    static_assert(is_in(arg, allowed_args_t{}));
}

8
投票

解包整数并使用折叠表达式:

template <typename AllowedIntegers>
struct contains
{};

template <typename Int, Int... Is>
struct contains<std::integer_sequence<Int, Is...>>
{
    template <Int value>
    static constexpr bool contains = ((value == Is) || ...);
};

// ...

template <int arg>
void foo()
{
    static_assert(contains<allowed_args_t>::contains<arg>);
}

Godbolt link

© www.soinside.com 2019 - 2024. All rights reserved.