-1

I have declared two functions:

template<typename T>
void foo(T& in) { cout << in; }
void foo(bool& b) { cout << "Bool:" << (b ? "True" : "False");}

I am calling the function like this:

bool var = false; foo(var);

I know I can write test code. But if this is a compiler dependent choice, writing test code will never have full coverage.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
xjsXjtu
  • 161
  • 2
  • 8
  • I mean invoke by: bool var = false; foo(var); – xjsXjtu Dec 27 '17 at 09:58
  • 1
    If it is a compiler dependent choice how can you expect to get a single answer? – Vivick Dec 27 '17 at 10:00
  • 2
    It isn’t compiler dependent (unless a compiler is in error). If a template and a nin-template are equally good matches, the non-template is preferred. BTW you can get `bool` formatted as a string using `out << std::boolalpha << true;` (the flag applies until it is reset). By default that would format as `true` (or `false`). If really necessary the string can be changed by using a custom `std::numpunct` facet. – Dietmar Kühl Dec 27 '17 at 10:01

2 Answers2

2

The second one, i.e.:

void foo(bool& b) { cout << "Bool:" << (b ? "True" : "False");}

since it will be a better match for bool var = false; foo(var);.

In general, overload resolutions favor non-templated methods over templated ones, as you can read in the ref:

Best viable function

F1 is determined to be a better function than F2 if implicit conversions [..]:

F1 is a non-template function while F2 is a template specialization


PS: This is not compiler-dependent, as there are rules that describe how the overload resolution occurs in such cases, as I mentioned above.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

Overload resolution usually prefers non-template functions over template functions. So the bool& version will be called. This is well-defined, not up to the compiler to decide.

For details, see cppreference, the section "Best viable function". (I could try linking to the Standard, but presumably it's even harder to read.)

Thomas
  • 174,939
  • 50
  • 355
  • 478