Is there a concept for ensuring that adding members to an existing class causes an error / warning in case the developer forgot to extend the methods that all members should handle?
If a class implements several methods that should concern all elements (for example, import / export), it is very easy to forget one or several methods for adaptation. The compiler would not recognize it, and the behavior would be as expected in many cases (except that you have the correct tests, of course.)
My current attempt is to check the class size in each method that could be forgotten silently. But of course, this is not easy to read, it is unsafe, and not regardless of the type of compiler / platform / assembly (therefore, I do not like it).
class C { int element1; int element2; int element3; <--- newly added without adapting operator==() public: void import_me(); void export_me(); bool operator== (const C&); void dump(); };
implementation may be hidden in different / large files:
void C::import_me(){ assert( sizeof( *this ) == 12 ); // this is my attempt of doing this read_fn( element1 ); read_fn( element2 ); read_fn( element3 ); } void C::export_me(){ assert( sizeof( *this ) == 12 ); // this is my attempt of doing this write_fn( element1 ); write_fn( element2 ); write_fn( element3 ); } /// the implementer forgot to adapt this method bool C::operator==(const C &other) { assert( sizeof( *this ) == 8 ); <--- this would fail if( element1 != other.element1 ) return false; if( element2 != other.element2 ) return false; return true; }
My next attempt is a macro that creates a matrix (X element method), which must be manually populated in each method, but it seems to me not very clean, and I doubt that it works well.
frans source share