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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With