Checking at compile time if specified value is in a range of a type

后端 未结 4 1713
难免孤独
难免孤独 2021-01-21 17:17

Is it possible to check this:

template
struct X{};

What I mean by this is, is it possible to check that va

4条回答
  •  难免孤独
    2021-01-21 18:13

    Now that you've changed X's signature from the way it was in the original unedited question, it's easily implemented using Boost.Integer:

    #include 
    #include 
    #include 
    
    template<
        typename IntType,
        boost::uint64_t Value,
        bool IsSigned = boost::integer_traits::is_signed
    >
    struct validate_range;
    
    template
    struct validate_range
    {
        typedef boost::integer_traits traits_t;
        static bool const value =
            static_cast(Value) >= traits_t::const_min &&
            static_cast(Value) <= traits_t::const_max;
    };
    
    template
    struct validate_range
    {
        typedef boost::integer_traits traits_t;
        static bool const value =
            Value >= traits_t::const_min &&
            Value <= traits_t::const_max;
    };
    
    template
    struct X
    {
        BOOST_STATIC_ASSERT_MSG(
            (validate_range::value),
            "Value constant is out of range"
        );
    };
    
    int main()
    {
        X x1;             // fails iif char is unsigned by default
        X x2;              // fine
        X x3;            // fails iif char is signed by default
        X x4;    // fails
        X x5;   // fine
        X x6;   // fails
    }
    

提交回复
热议问题