/////////////////////////////////////////////////////////////// // enforce.cpp - Assert-like error handler // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2005 // // Source: Andrei Alexandrescu and Petru Marginean // // Enforcements, C/C++ User's Journal, June 2003 // /////////////////////////////////////////////////////////////// // Note: // // I have simply made some cosmetic changes. The code is // // due, in total, to the efforts of Andrei and Petru. // /////////////////////////////////////////////////////////////// #ifdef TEST_ENFORCE // This file is just a test driver and is not needed for // applications. The compilation conditional above is included // just in case a user includes this file in a build. #include "enforce.h" #include int* simulateSuccess() { static int i = 0; return &i; } int* simulateError() { return 0; } void foo(int* pInt) { } struct Widget { void print() { std::cout << 1 << ". This is the Widget!" << std::endl; } }; Widget* makeWidget() { static Widget o; return &o; } // int main() { std::cout << "\n Demonstrating Enforcer Module" << "\n ===============================\n\n"; try { ENFORCE(simulateSuccess()); // ENFORCE returns the value returned by its argument, e.g., // the pointer to int returned by simulateSuccess() int* pInt = ENFORCE(simulateSuccess())("You should not ")("see")(" this message."); // You can supply as many arguments in parens as you need to describe // the potential error. These can be anything you would pass to cout. Widget* pObj = ENFORCE(makeWidget())("Hopefully you don't ")("see this either!"); pObj->print(); foo( ENFORCE(simulateError())(2)(". An exception will be thrown ") ("below.\n") ); } catch (const std::exception& e) { std::cout << e.what() << "\n\n"; std::cout.flush(); } return 0; } #endif