Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_assert for ensuring design contract

Tags:

c++

iterator

As a part of a team of developers, I wanted to ensure that a set of functions (and operators) are implemented on the custom iterators that we publish. Using STL iterator types as base types help, however due to some reasons(outside my control) we decide not to enforce STL compatibility. The iterators are consumed by the same team and by people across the company.

I wanted to design a template class that consumes the iterator type and tests against the design contract.

For example, I would expect an iterator to implement a operator++ , operator-- and also declare the required typedefs.

1> Is it possible to implement such a template class that enforces the design contract ? probably using static_assert ?

2> If yes, is this a good design ?

reference : custom iterator

like image 378
Ram Avatar asked Sep 20 '12 09:09

Ram


2 Answers

Is it possible to implement such a template class that enforces the design contract ? probably using static_assert ?

For checking whether specific method exists (very similar to this example) :

struct Hello
{
};

struct Generic {
    int operator++()
    {
        return 5;
    }
};


// SFINAE test
template <typename T>
class has_operator_plusplus
{
    typedef char one;
    typedef long two;

    template <typename C> static one test( decltype(&C::operator++) ) ;
    template <typename C> static two test(...);

public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};


int main(int argc, char *argv[])
{
    // the first check breaks the build
    //static_assert( has_operator_plusplus<Hello>::value, "has no operator" );
    static_assert( has_operator_plusplus<Generic>::value, "has no operator" );
}

is this a good design ?

Yes, because by breaking the build, the error is caught very fast, and the user of the class doesn´t have to read the documentation (most people usually skip that part when programming)

like image 178
BЈовић Avatar answered Nov 06 '22 00:11

BЈовић


Yes, you can implement such a template class. You can use SFINAE to test for the presence of various members and if they're not correct, static_assert. Although I'm not sure why you'd want to define typedefs in a C++11 world.

It's always a good idea to do additional checking on your code.

like image 20
Puppy Avatar answered Nov 06 '22 00:11

Puppy