Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build switch-case with variadic templates

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; }
like image 724
Khurshid Normuradov Avatar asked Sep 12 '13 06:09

Khurshid Normuradov


1 Answers

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

like image 109
Angew is no longer proud of SO Avatar answered Oct 13 '22 02:10

Angew is no longer proud of SO