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

后端 未结 4 1675
难免孤独
难免孤独 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:00

    I would say that the direct solution to this question might be this:

       template< typename T, T X, T L, T H>
          using inside_t = 
            std::enable_if_t< (X <= H) && (X >= L), 
               std::integral_constant >;
    

    Applied to the OP:

        template    struct X; // final {};
    
    template
    struct X final 
    {
        using ascii_ordinal = inside_t;
        char value = char(ascii_ordinal::value);
    };
    

    Which renders really terrible CL error messages when it does the job:

    X a; //here 300 is out of range and I would like to be able to detect that.
    

    While much less snazzy but most comfortable API might be:

    template
    struct X final 
    {
        static_assert( K >= 0U && K <= 127U, "\n\nTeribly sorry, but value must be between 0 and 127 inclusive\n\n") ;
        char value = char(K);
    };
    

提交回复
热议问题