Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 802
PiotrK Avatar asked Nov 29 '22 08:11

PiotrK


1 Answers

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{}));
}
like image 68
Jarod42 Avatar answered Dec 05 '22 18:12

Jarod42