I want to build function, like as:
template< int ... values>
constexpr bool check( int i ) noexcept
{
switch(i)
{
case values[0]: case values[1]: ... case values[n-1] : // only illustrated.
return true;
default: return false;
}
}
Can I make that function?
UPDATE: thanks, now i know how to implement:
template< int ... values> struct checker;
template< int head, int ... tail> struct checker<head, tail...>
{
static constexpr bool apply( int i ) noexcept {
return i == head || checker<tail...>::apply(i);
}
};
template<> struct checker<>
{
static constexpr bool apply( int ) noexcept { return false; }
};
template< int ... values >
constexpr bool check(int i) noexcept { return checker<values...>::apply(i); }
UPDATE2: I don't know, it's good or not, but i found this solution :
template<size_t N>
constexpr bool any_of( bool( && array)[N], size_t index = 0) noexcept
{
return (index == N ) ? false
: ( array[index] || any_of( std::forward< decltype(array)>(array), 1+index) );
}
template< int ... values >
constexpr bool check(int i) noexcept
{
using list = bool[sizeof...(values)];
return any_of( list{ ( i == values) ... } );
}
template<>
constexpr bool check <>(int i) noexcept { return false; }
I don't think it's possible to use the switch
syntax in any way. But this should work:
template < int head, int ... values >
struct checker
{
static constexpr bool value(int i) noexcept
{ return i == head || checker<values...>::value(i); }
};
template < int head >
struct checker<head>
{
static constexpr bool value(int i) noexcept
{ return i == head; }
};
template< int ... values>
constexpr bool check( int i ) noexcept
{
return checker<values...>::value(i);
}
Live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With