relational::operator bool()

Douglas Gregor gregod at cs.rpi.edu
Wed Nov 14 15:44:43 CET 2001


Hello,
  This is just a C++ nitpick, but operator bool() is often considered harmful 
because of the plethora of implicit conversions (bool->int being the worst of 
these implicit conversions, IMHO). I'm not suggesting that operator bool() be 
removed from relational, but instead replace it with a safer construct.
  Within the Boost C++ libraries (http://www.boost.org), we've adopted a 
"safe_bool" conversion using of a pointer-to-member function. The trick can 
be illustrated concisely:

// Add to class relational
  private:
    struct dummy {
      void nonnull() {};
    };

    typedef void (dummy::*safe_bool)();

   safe_bool make_safe_bool(bool cond) const
      { return cond?  &dummy::nonnull : 0; }

Then in relational::operator safe_bool() const,  whereever there is a 
"return <bool-expression>", it should be replaced with 
"return make_safe_bool(<bool-expression>)".

The use of the pointer-to-member function eliminates implicit conversions, 
but the relational class can still be used in a boolean context (since it is 
evaluated as "is the pointer-to-member function null?"). All meaningless 
operations that are allowed by a "bool" conversion except for == and != are 
eleminated by this "safe_bool".

I can submit a patch against CVS if needed.

	Doug Gregor
	gregod at cs.rpi.edu



More information about the GiNaC-devel mailing list