Psuedo code, but...
Something along the lines of:
Code:
int main()
{
char mychar;
int myint;
char* c = safe_cast<char>(mychar); // Compiles
c = safe_cast<char>(myint); // Won't compile
}
template<typename NewType, typename OriginalType>
NewType& safe_cast(Original& Data)
{
STATIC_ASSERT(sizeof(NewType) == sizeof(OriginalType));
return (NewType)Data;
}
This is dependant on boost's STATIC_ASSERT (or what it's called; can't remember 100% macro.
There are more ways to do this, of course, but this is the easy way.
I haven't checked if this will compile, so it may contain a few errors, but the theory is sound.
And in you don't want to use boost, you can just the compiler to complain.
Something like:
Code:
int main()
{
char mychar;
int myint;
char* c = safe_cast<char>(mychar); // Compiles
c = safe_cast<char>(myint); // Won't compile
}
template<bool bFail>
struct dummy { static const bool bFail; };
template<>
struct dummy<true> { static const bool bFail = 'a'; }; // Causes a compile error about conversion from char to bool on purpose
template<>
struct dummy<false> { static const bool bFail = false; };
template<typename NewType, typename OriginalType>
NewType& safe_cast(Original& Data)
{
dummy< sizeof(NewType) != sizeof(OriginalType) >::bFail;
return (NewType)Data;
}