代码之家  ›  专栏  ›  技术社区  ›  PiotrK

如何在编译时找出整数序列是否包含给定的数字?

  •  4
  • PiotrK  · 技术社区  · 7 年前

    鉴于:

    typedef std::integer_sequence<int, 0,4,7> allowed_args_t;
    

    template<int arg> void foo()
    {
        static_assert( /*fire if arg not in allowed_args_t!*/ )
    }
    

    static_assert 在编译时尽可能便宜?

    2 回复  |  直到 7 年前
        1
  •  13
  •   PiotrK    7 年前

    您可能需要使用:

    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{}));
    }
    
        2
  •  8
  •   Justin    7 年前

    解压整数并使用折叠表达式:

    template <typename AllowedIntegers>
    struct contains
    {};
    
    template <typename Int, Int... Is>
    struct contains<std::integer_sequence<Int, Is...>>
    {
        template <Int value>
        static constexpr bool contains = ((value == Is) || ...);
    };
    
    // ...
    
    template <int arg>
    void foo()
    {
        static_assert(contains<allowed_args_t>::contains<arg>);
    }
    

    Godbolt link