Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing variable constraints in C++

I've been looking for an example that shows how to implement constraints in C++ (or a boost library that lets me do this easily), but without much luck. The best I could come up with off the top of 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 there's probably some more functionality you'd want from a constraint class. This is just an idea for a starting point.

Anyway, the problem I see is that I have to overload all operators that T defines in order to make it really behave like a T, and there is no way for me to find out what those are. Now, I don't actually need constraints for that many different types, so I could just leave out the template and hard code them. Still, I'm wondering if there's a general (or at least more succint/elegant) solution or if there's anything seriously wrong with my approach.

like image 552
drby Avatar asked Dec 18 '22 08:12

drby


1 Answers

Looks good as for tiny example. But be sure to implement all the operators and handle somehow wrong values.

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

Use boost operators to help you with operators overload.

And probably it would be good to have an option as a template parameter: either exception or assertion.

I'd use such class. It is always better to have an index parameter that auto check vector range and do assertion.

void foo( VectorIndex i );
like image 93
Mykola Golubyev Avatar answered Dec 26 '22 00:12

Mykola Golubyev