【问题标题】:How to build switch-case with variadic templates如何使用可变参数模板构建 switch-case
【发布时间】:2013-09-12 17:31:50
【问题描述】:

我想构建函数,比如:

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

【问题讨论】:

    标签: c++ c++11 variadic-templates


    【解决方案1】:

    我认为不可能以任何方式使用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);
    }
    

    Live example

    【讨论】:

    • “我认为不可能以任何方式使用 switch 语法” 至少,在 C++11 中的 constexpr 函数中,与包扩展问题无关。
    • @DyP 谢谢。我在工作中被 VS2010 困住了,所以我并没有真正内部化 constexpr 规则。
    • 同样的原因你不能使用if ;)
    • 顺便说一句。通过std::integral_constant&lt;bool, ..&gt;true_typefalse_type)调度标签使得只使用check 的两个函数重载而不是使用辅助类成为可能。
    • @KhurshidNormuradov Live example
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2016-12-01
    • 2019-08-25
    相关资源
    最近更新 更多