Item 45. bool

Source: Internet
Author: User
Tags builtin
Item 45. bool

Difficulty: 7

Do we really need a builtinBoolType? Why not just emulate it in the existing language? This item reveals the answer.

BesidesWchar_t(Which wasTypedefIn C ),BoolIs the only builtin type to be added to C ++ since the arm (ellis90 ).

CocouldBool'S effect have been duplicated without adding a builtin type? If yes, show an equivalent implementation. If no, show why possible implementations do not behave the same as the builtinBool.

 

Solution

The answer is: no,Bool'S effect cocould not have been duplicated without adding a builtin type.BoolBuiltin type, and the reserved keywordsTrueAndFalse, Were added to C ++ precisely because they couldn't be duplicated completely using the existing language.

This item is intended to define strate the considerations you have to think about when you design your own classes,EnumS, and other tools.

The second part of the item question was: If no, show why possible implementations do not behave the same as the builtinBool.

There are four major implementations.

Option 1: Typedef(Score: 8.5/10)

This option means"Typedef <something> bool;", Typically:

// Option 1: typedef //typedef int bool;const bool true  = 1;const bool false = 0;

This solution isn' t bad, But it doesn' t allow Overloading onBool. For example:

// file f.h void f( int  ); // okvoid f( bool ); // ok, redeclares the same function// file f.cppvoid f( int  ) { /*...*/ }  // okvoid f( bool ) { /*...*/ }  // error, redefinition

Another problem is that option 1 can allow code like this to behave unexpectedly:

void f( bool b ) {  assert( b != true && b != false );  }

So option 1 isn' t good enough.

Option 2: # Define(Score: 0/10)

This option means"# Define bool<Something> ", typically:

// Option 2: #define //#define bool  int#define true  1#define false 0

This is, of course, purely edevil. It not only has all the same problems as option 1, but it also wreaks the usual havoc# DefineS. For example, pity the poor customer who tries to use this library and already has a variable namedFalse; Now this definitely behaves differently from a builtin type.

Trying to use the Preprocessor to simulate a type is just a bad idea.

Option 3: Enum(Score: 9/10)

This option means to make"Enum bool", Typically:

// Option 3: enum //enum bool { false, true };

This is somewhat better than option 1. it allows overloading (the main problem with the first option), but it doesn' t allow automatic conversions from a conditional expression (which wowould have been possible with the first option), to wit:

bool b; b = ( i == j );

This doesn' t work, becauseIntS cannot be implicitly convertedEnumS.

Option 4: Class(Score: 9/10)

Hey, this is an object-oriented language, right? So why not write a class, typically:

class bool {public:  bool();  bool( int );            // to enable conversions from  bool& operator=( int ); //  conditional expressions  //operator int();   // questionable!  //operator void*(); // questionable!private:  unsigned char b_;};const bool true ( 1 );const bool false( 0 );

This works cannot be used for the conversion operators marked "questionable." They're questionable because:

  • With an automatic conversion,BoolS will interfere with overload resolution, just as do all classes having non-Explicit(Conversion) constructors and/or implicit conversion operators, especially when the conversion is from or to a common type. See items 20 and 39 for more about Implicit conversions.

  • Without a conversion to something likeIntOrVoid *,BoolObjects can't be tested "naturally" in conditions. For example:

    bool b; /*...*/if( b ) // error without an automatic conversion to{       // something like int or void*    /*...*/}

It's a classic catch-22 situation: we must choose one alternative or the other provided ither provide an automatic conversion or not exist ut neither option lets us duplicate the effect of having a builtinBoolType. In summary:

  • ATypedef... boolWouldn't allow Overloading on bool.

  • A# Define boolWouldn't allow overloading either and wocould wreak the usual havoc# DefineS.

  • AnEnum boolWocould allow overloading but couldn't be automatically converted from a conditional expression (as in"B = (I = J );").

  • AClass boolWocould allow overloading but wouldn't letBoolObject be tested in conditions (as in"If (B)") Unless it provided an automatic conversion to something likeIntOrVoid *, Which wocould wreak the usual havoc of automatic conversions.

And, finally, there's one more thing (related to overloading) that we couldn't have done otherwise, either, doesn t perhaps with the last option: specify that conditional expressions have typeBool.

So, yes, we really did need a builtinBool.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.