As those classes have no relationship, I see now way to do this because you have to be explicit about witch types you want to be checked.
The only DRY way to enforce this is what Nikolai N Festissov proposed. I was writting a similar example with some minor modifications, but the global idea is to make a boost::nocopy - like class that will force the child class to be of a given size.
template< typename CheckedType, size_t FixedSize >
class SizeChecked // simple, no inheritance overload
{
public:
SizeChecked()
{
// c++0x or compilers with static_assert() available
//static_assert( sizeof( CheckedType ) == FixedSize, "Type size check failed!" );
BOOST_STATIC_ASSERT( sizeof( CheckedType ) == FixedSize );
}
};
template< typename CheckedType >
class Size512 : public SizeChecked< CheckedType, 512 > // simple, no inheritance overload
{};
////////////////////////////////////////////////////////////////////
class A : Size512< A > // automatically check
{
};
class B : Size512< B > // automatically check
{
std::array< char, 512 > m_array;
};
class C : SizeChecked< C, 1 >
{
char m_char;
};
class D : SizeChecked< D, 4 >
{
short m_k;
char m_u;
};
int wmain()
{
// need instantiation to be checked !
//A a; // will trigger the assertion at compile time
B b; // sizeof(B) == 512 : will be fine
C c; // sizeof(C) == 1 : will be fine
//D d; // will fail because sizeof( short ) + sizeof( char ) != 4 !
}
Beware : if you loose inheritance you still have to provide an explicit check on the child classes, the check is not inherited!
By the way, a possible way to be more DRY would be to put all your static assertion in only one place.