Limiting range of value types in C++

前端 未结 9 814
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 10:33

Suppose I have a LimitedValue class which holds a value, and is parameterized on int types \'min\' and \'max\'. You\'d use it as a container for holding values which can on

9条回答
  •  情话喂你
    2020-11-28 11:10

    The bounded::integer library does what you want (for integer types only). http://doublewise.net/c++/bounded/

    (In the interests of full disclosure, I am the author of this library)

    It differs from other libraries that attempt to provide "safe integers" in a significant way: it tracks integer bounds. I think this is best shown by example:

    auto x = bounded::checked_integer<0, 7>(f());
    auto y = 7_bi;
    auto z = x + y;
    // decltype(z) == bounded::checked_integer<7, 14>
    static_assert(z >= 7_bi);
    static_assert(z <= 14_bi);
    

    x is an integer type that is between 0 and 7. y is an integer type between 7 and 7. z is an integer type between 7 and 14. All of this information is known at compile time, which is why we are able to static_assert on it, even though the value of z is not a compile-time constant.

    z = 10_bi;
    z = x;
    static_assert(!std::is_assignable::value);
    

    The first assignment, z = 10_bi, is unchecked. This is because the compiler can prove that 10 falls within the range of z.

    The second assignment, z = x, checks that the value of x is within the range of z. If not, it throws an exception (the exact behavior depends on the type of integer you use, there are many policies of what to do).

    The third line, the static_assert, shows that it is a compile-time error to assign from a type that has no overlap at all. The compiler already knows this is an error and stops you.

    The library does not implicitly convert to the underlying type, as this can cause many situations where you try to prevent something but it happens due to conversions. It does allow explicit conversion.

提交回复
热议问题