TITLE: safety and speed, a stack example (Source: comp.lang.c++.moderated, 9 March 2001) [ Note that it is not a requirement that I agree with an author's posting in order to be in this list. Its enough that the content be technically interesting. -adc ] ANDREI: "Andrei Alexandrescu" > No, if you design a truly reusable stack facility, you should leave the > exact way of handling errors up to the user of your IntStack component. > So the users who want safety use a checked version, and those who need > speed use an unchecked version. The default is checked. > > The means of customizing components in this way is described at large in > my book (http://moderncppdesign.com), but in essence it looks like so: > > struct NoCheck > { > static void OnError() {} > }; > > struct AssertCheck > { > static void OnError() { assert(false); } > }; > > struct StrictCheck > { > static void OnError() > { throw std::runtime_error("Runtime error blah blah"); } > }; > > template > class IntStack : private CheckingPolicy > { > ... > int pop() > { > if (empty()) CheckingPolicy::OnError(); > ... > } > }; NARAN: "Siemel Naran" This will grow to be unmangeable. For every function that receives an IntStack will have to be templatized, adding to the compile and link time complexity of the program. And things are made worse by the fact that most compilers do not support the 'export' keyword. IMHO, a better idea is to provide two pop functions -- one that does the check and one that does not. The one that does the check will perform the check and then call the one that does not do the check, and it will be templatized or polymorphicized to provide for error handling in a variety of ways, and if a template it will be inline to save us from putting template code into the .cc file. // Template version // example class class Assert { public: void operator()(bool arg) const { assert(arg); } }; class IntStack : private CheckingPolicy { ... int pop(); template int pop(Assert assert) { assert(empty()); // calls Assert::operator() return pop(); } }; // Polymorphic version class Assert { public: virtual ~Assert(); virtual void operator()(bool arg) const { assert(arg); } }; class IntStack : private CheckingPolicy { ... int pop(); int pop(const Assert& assert) { assert(empty()); // calls virtual Assert::operator() return pop(); } }; ANDREI: > Of course a refined version would include more explanatory messages etc. NARAN: In the new version just write a new assert object. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com