//: C05:StaticAssert2.cpp {-g++} // From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison. // (c) 1995-2004 MindView, Inc. All Rights Reserved. // See source code use permissions stated in the file 'License.txt', // distributed with the code package available at www.MindView.net. #include using namespace std; // A template and a specialization template struct StaticCheck { StaticCheck(...); }; template<> struct StaticCheck {}; // The macro (generates a local class) #define STATIC_CHECK(expr, msg) { \ class Error_##msg {}; \ sizeof((StaticCheck(Error_##msg()))); \ } // Detects narrowing conversions template To safe_cast(From from) { STATIC_CHECK(sizeof(From) <= sizeof(To), NarrowingConversion); return reinterpret_cast(from); } int main() { void* p = 0; int i = safe_cast(p); cout << "int cast okay" << endl; //! char c = safe_cast(p); } ///:~