Implement variable constraints in C ++

I was looking for an example that shows how to implement restrictions in C ++ (or the boost library, which allows me to do this easily), but without much luck. The best I could think of from my head is:

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>

template<typename T>
class constrained
{
    public:
        constrained(boost::function<bool (T)> constraint, T defaultValue, T value = defaultValue)
        {
            ASSERT(constraint(defaultValue));
            ASSERT(constraint(value));

            this->value = value;
            this->defaultValue = defaultValue;          
            this->constraint = constraint;                      
        }

        void operator=(const T &assignedValue)
        {
            if(constraint(assignedValue))
                value = assignedValue;      
        }   

    private:
        T value;
        T defaultValue;
        boost::function<bool (T)> constraint;
};

int main(int argc, char* argv[])
{
    constrained<int> foo(boost::lambda::_1 > 0 && boost::lambda::_1 < 100, 5, 10);

    foo = 20; // works
    foo = -20; // fails

    return 0;
}

Of course, you may need some more functionality from the class of restrictions. This is just an idea for a starting point.

, , , , T , T, , . , . , , (, , succint/elegant) - .

+3
6

, . .

foo = 100; // works
++foo; // should throw an exception or perform an assert

, .

, , : , .

. , .

void foo( VectorIndex i );
+4

, , , , , constrained<T>, .

(=, + =, - =, * =,/=,% =, & =, | =, ^ =, <= lt; =, → = pre post ++, pre post -) T:

template<typename T>
class constrained {
    ... // As before, plus overloads for all mutating operators
public:
    operator T() const {
        return value;
    }
};

, , constrained<T> (, x + y, x int y constrained<int>), rvalue T, . , - constrained<T> - , T constrained<T>, constrained<T> .

+3

, .

, , .

- , , (, ++()), , , , .

, .

+2

Boost.Constrained_Value . , Boost. IIRC, , .

+2

, , , , ?

+1

Boost ( , ). ( , ). , , :

: -, , , .

0

Source: https://habr.com/ru/post/1706447/