template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECK(expr,msg) {CompileTimeError< ((expr)!=0) > Error_##msg; (void)Error_##msg; }
template <class To , class From>
To safe_reinterpret_cast(From from)
{
STATIC_CHECK(sizeof(From) <= sizeof(To),Destination_Type_Too_Narrow);
return reinterpret_cast<To>(from);
}
void main()
{
void *p= NULL;
char c= safe_reinterpret_cast<char>(p);
}
Above code works fine and gives compile time error when we try to convert pointer to char . But its not very clear how STATIC_CHECK macro works.
As per above code it should lead to following
STATC_CHECK(false,Destination_Type_Too_Narrow)
Above macro will get expanded as follows:
CompileTimeError<false>
ERROR_Destination_Type_Too_Narrow;
(void)ERROR_Destination_Type_Too_Narrow;
In above macro I am not able to understand what these two statements are meant for
ERROR_Destination_Type_Too_Narrow;
(void)ERROR_Destination_Type_Too_Narrow;
If anyone having clear understanding please explain
We have specialization for class CompileTimeError<true>
, that has default constructor. Instanciations of other cases will cause error, that CompileTimeError<not true>
is undefined type (in your case we trying to create variable ERROR_Destination_Type_Too_Narrow
of type CompileTimeError<false>
). (void)VariableName
is only silence of -Wunused