Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

c++ - Why does a quoted string match bool method signature before a std::string?

Given the following methods:

// Method 1
void add(const std::string& header, bool replace);

//Method 2
void add(const std::string& name, const std::string& value);

It would appear that the following code will end up calling method 1 instead of method 2:

something.add("Hello", "World");

I ended up creating another method that looks like this:

//Method 3
void MyClass::add(const char* name, const char* value) {
    add(std::string(name), std::string(value));
}

It worked. So it would seem that when a method accepts a "quoted string" it will match in the following order:

  1. const char*
  2. bool
  3. std::string

Why would a quoted string be treated as a bool before a std::string? Is this the usual behavior? I have written a decent amount of code for this project and haven't had any other issues with the wrong method signature being selected...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My guess is the conversion from pointer to bool is an implicit primitive type conversion, where the conversion to std::string requires the call of a constructor and the construction of a temporary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...