Boolean and string overload of the destination operator (C ++)

I define several overloads of the assignment operator as follows:

foo.h

class Foo
{
private:
    bool my_bool;
    int my_int;
    std::string my_string;
public:
    Foo& operator= (bool value);
    Foo& operator= (int value);
    Foo& operator= (const std::string& value);
};

foo.cpp

// Assignment Operators.
Foo& Foo::operator= (bool value) {my_bool = value; return *this;}
Foo& Foo::operator= (int value) {my_int = value; return *this;}
Foo& Foo::operator= (const std::string& value) {my_string = value; return *this;}

And here is my main.cpp (see comment marked SURPRISE):

Foo boolFoo;
Foo intFoo;
Foo stringFoo;

// Reassign values via appropriate assignment operator.
boolFoo = true;                // works...assigned as bool
intFoo = 42;                   // works...assigned as int
stringFoo = "i_am_a_string";   // SURPRISE...assigned as bool, not string

std::string s = "i_am_a_string";
stringFoo = s;                 // works...assigned as string

// works...but awkward
stringFoo = static_cast<std::string>("i_am_a_string");

Question: Can someone tell me why the string literal is not passed in a boolean context?

+5
source share
2 answers

The C ++ standard defines the rules for resolving overloads in chapter 13.3, where you will find:

13.3.3.2 Ranking of implicit conversion sequences [over.ics.rank]

2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1)

- (13.3.3.1.1) , ,

- (13.3.3.1.2) , (13.3.3.1.3).

, bool int, . , ? :

4.2 [conv.array]

1 lvalue rvalue " N T" " T" prvalue " T". .

, const char[N], const char*. :

4.12 [conv.bool]

1 , , prvalue bool. , false; true. std::nullptr_t prvalue bool; false.

bool. , std::string .

, , const char* const std::string&.

+9

.

, std::string , , - . , , , "hi world", std::string, , bool, " " & dagger; type std::string.

, : ++.

& dagger; , , , , .

+3

All Articles