"Simon Elliott" <Simon at ctsn.co.uk> wrote in message
news:42***********************@news.gradwell.net.. .
#include <iostream>
#include <string>
static void Test(const std::string& t)
{
std::cout << "std::string: " << t <<std::endl;
}
static void Test(bool t)
{
std::cout << "bool: " << t <<std::endl;
}
int main(int argc, char* argv[])
{
std::string t1 = "t1";
bool t2 = true;
char t3[] = "t3";
std::cout << "std::string" <<std::endl;
Test(t1);
std::cout << "bool" <<std::endl;
Test(t2);
std::cout << "char array" <<std::endl;
Test(t3);
return 0;
}
Output:
std::string
std::string: t1
bool
bool: 1
char array
bool: 1
Why does a call to Test with a char array map to
static void Test(bool t)?
I'd have expected it to either map to
static void Test(const std::string& t)
or give a compile time error.
I think I know this one. (I could be wrong. It happened once or twice
before. :-))
The implicit conversion of a char array to a bool takes place because a char
array can be seen as a pointer (to the first character of the array). And a
pointer can be implicitly converted to a bool in order to allow testing for
NULL with statements like "if (ptr) {...}". So since there is an available
conversion, the compiler uses it.
It won't try to convert to std::string, because the types are unrelated.
There is an operator = and a constructor for std::string which take a char
array (pointer), but neither of those is used here. If you want to call the
string version, then you need to first construct a string using that array
and then pass the string.
If that's not the function you wanted to call, then what exactly did you
_want_ to happen? (Not a compile error, I assume? :-))
-Howard