1

When I run the below test program, I would have expected that the string literal matches the std::string constructor, instead the bool version is called. I wonder how this is covered in the standard and I sure don't understand why this is converted to a bool. When I replace the bool with [unsigned] intit works as expected.

#include <iostream>
#include <string>

class Test
{
public:
    Test(bool value)
    {
        std::cout << "BOOL constructor: " << value << std::endl;
    }

    Test(std::string value)
    {
        std::cout << "string constructor: " << value << std::endl;
    }
};


int main()
{
    Test t0(true);
    Test t1(false);
    Test t2(2);
    Test t3("TEST1");

    std::string ts = "string";
    Test t4(ts);
}

Output bool:

BOOL constructor: 1 BOOL constructor: 0 BOOL constructor: 1 BOOL constructor: 1 string constructor: string

Output int:

BOOL constructor: 1 BOOL constructor: 0 BOOL constructor: 2 string constructor: TEST1 string constructor: string

Devolus
  • 21,661
  • 13
  • 66
  • 113

0 Answers0