Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual C++ 2010 accepts string for bool in overloaded function

I am using Visual Studio 2012 (But using the VC++ 2010 build tools), and I have these two overloaded functions (signatures below) defined in a class which I later call in another class that instantiates the first class (also below):

Defined in the class:
Node CreateNode(Node *parent,string name,string node_text,bool expects_node = true);
Node CreateNode(Node *parent,string name, string attribute, string value,bool expects_node = true)

Calling these functions in the macro:
Node axis1 = handler->CreateNode(&sparse,"axis","id","trigger_pt");

When I make the function call, it calls the first function, not the second! So it treats the second string as a boolean! However, when I add "true" to the function call, it calls the second function as expected. Can anyone explain this? Thanks!

like image 411
MartyC Avatar asked Mar 25 '13 19:03

MartyC


1 Answers

The string literal "trigger_pt" is of type "array of 11 const char". The compiler considers it better to convert this to a bool than to convert it to a std::string. The reason is because converting to bool only uses standard conversions (array-to-pointer and then pointer to bool), whereas converting to std::string requires calling a constructor. A standard conversion sequence is always considered better than a user-defined conversion sequence (involving the conversion constructor).

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

  • a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and
  • [...]

You can force it to use the second overload by making that literal a std::string:

Node axis1 = handler->CreateNode(&sparse,"axis","id",std::string("trigger_pt"));

The other alternative is to provide another overload that takes a const char*, which will be preferred over the bool version. This overload can simply forward to the std::string overload.

like image 191
Joseph Mansfield Avatar answered Oct 25 '22 07:10

Joseph Mansfield