ycshao
ycshao

Reputation: 1958

Why conditional operator will be treated as bool when passed in as a parameter?

I have two overloaded function

void foo(std::string value);
void foo(bool value);

when I call it with

foo(true ? "a" : "b");

why function takes a boolean will be called instead of string?

Upvotes: 3

Views: 130

Answers (1)

juanchopanza
juanchopanza

Reputation: 227370

The bool overload provides a better match, since you get an conversion between a const char* and bool. The string overload requires a conversion to a user defined type.

The conditional operator has nothing to do with it. For example,

#include <string>
#include <iostream>

void foo(bool) { std::cout << "bool" << std::endl;  }

void foo(std::string) { std::cout << "string" << std::endl; }

int main()
{
  foo("a");
}

Output:

bool

If you were to provide an overload

void foo(const char*) {}

then that one would be called.

Upvotes: 10

Related Questions