如何使用可变参数模板构建开关盒

How to build switch-case with variadic templates

本文关键字:构建 开关 参数 何使用 变参      更新时间:2023-10-16

我想构建函数,如下所示:

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

我可以制作该功能吗?

更新:谢谢,现在我知道如何实现:

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:我不知道,好不好,但我找到了这个解决方案:

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

我认为不可能以任何方式使用switch语法。但这应该有效:

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

现场示例