Static_assert for securing a project contract

As part of the development team, I wanted to make sure that the set of functions (and operators) is implemented on the custom iterators that we publish. Using STL iterator types as base types helps, however, for some reason (out of my control), we decided not to use STL compatibility. Iterators are consumed by one team and people in the company.

I wanted to create a template class that uses an iterator type and tests it against a design contract.

For example, I would expect the iterator to execute the operator ++, operator--, and also declare the required typedef.

1> Is it possible to implement such a template template that will fulfill the design contract? perhaps using static_assert?

2> If so, is this a good design?

link: custom iterator

+8
c ++ iterator design
source share
2 answers

Is it possible to implement such a template that will fulfill the project contract? perhaps using static_assert?

To check for a specific method (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, after breaking the assembly, the error is caught very quickly, and the class user should not read the documentation (most people usually skip this part when programming)

+10
source share

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

It is always useful to perform additional code verification.

+2
source share

All Articles