Constrained vs. restricted value types

In truth, not by very much. Boost’s constrained values use more template metaprogramming magic for reasons I’ve not been able to fully figure out. In the end, their code also boils down to what Fhtagn!’s code boils down to: prior to assigning a value, a check function is invoked that is handed the value to be assigned. If this new value does not meet the required criteria, something other than assignment happens.

In Fhtagn!’s approach, this is all decided by a check function of this form:

1
2
3
4
5
6
7
8
9
10
11
template <
    typename valueT,
    typename next_restrictionT = none<valueT>
>
struct my_check
{
    static inline valueT const & check(valueT const & value)
    {
      // magic happens here
    }
};

Here the check() function performs up to three tasks:

  1. It checks whether the new value meets some criteria.
  2. If the check fails, it performs error handling of the sort that the user desires. In Fhtagn!’s pre-built check functions, exceptions are thrown.
  3. If the check succeeds, the new value is returned so it can be assigned to the restricted variable.

That prototype/behaviour allows the user to provide check functions that, perhaps, bound values to a certain range, or return default values if the value does not meet the desired criteria. In boost’s version, the same is possible, but the error handling and value checking is separated.

And that’s about the difference I can see. I prefer Fhtagn!’s approach because of it’s relative simplicity. Other people may prefer boost’s approach because of it’s greater reusability1.

Whichever approach/implementation you choose, the aim of both is to provide better protection from careless programming. If you write your function prototypes with the help of restricted value types, not only can you rest assured that no “evil” values make it to your function body, you also signal to the user how your function is meant to be used — in code, not in documentation. Both are invaluable.

  1. In Fhtagn!, it’s impossible to reuse the predefined even restriction but have it not throw an expection. []

Pages: 1 2

One Response to “Constrained vs. restricted value types”

  1. Constrained vs. restricted value types | un|we|sen Says:

    [...] you’re interested in more detail, head over to the orignal article on the Fhtagn! website. [...]


Copyright © 2007 - 2017 by the respective authors.
Permission to use the image of Great Cthulhu has kindly been granted by F. Launet/Goomi Studio.
Other content on this website is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.0 Germany License.
Creative Commons License


Blog directory