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

Pio*_*trK 4 c++ variadic-templates c++17

鉴于:

typedef std::integer_sequence<int, 0,4,7> allowed_args_t;
Run Code Online (Sandbox Code Playgroud)

和:

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

我应该怎么写这个static_assert在编译时尽可能便宜?

我正在使用C++ 17.

Jar*_*d42 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{}));
}
Run Code Online (Sandbox Code Playgroud)

  • 在C++ 20中使用模板lambdas会很好,所以我们可以内联这些:https://wandbox.org/permlink/hT6R6SxcEQtVFcsj (2认同)

Jus*_*tin 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>);
}
Run Code Online (Sandbox Code Playgroud)

Godbolt链接