简体   繁体   中英

How to find out if integer_sequence contains given number in compile-time?

Given:

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

and:

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

How should I write that static_assert to be as cheap as possible in compile-time?

I'm using C++17.

You might want to use:

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{}));
}

Unpack the integers and use a fold expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM