mardi 4 octobre 2016

Overloading, variadic functions and bool type

Following program compiles fine and works as expected. Its output is:

1
2

#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(int a, const char* b, ...) { printf("2\n"); };
};

int main()
{
  Foo foo1;
  foo1.Bar("Test", "xx", 1, 2);
  foo1.Bar(1, "xx", "xx", 2, 2);
}

Now if I change the int parameter of the second Bar function into bool and foo1.Bar(1, "xx", "xx", 2, 2); into foo1.Bar(true, "xx", "xx", 2, 2);, then the following line won't compile and I get the error: 'Foo::Bar': 2 overloads have similar conversions:

  foo1.Bar("Test", "xx", 1, 2);

The whole program that doesn't compile:

#include <stdio.h>

class Foo
{
public:
  void Bar(const char* b, ...) { printf("1\n"); };
  void Bar(bool a, const char* b, ...) { printf("2\n"); };
};

int main()
{
  Foo foo1;
  foo1.Bar("Test", "xx", 1, 2);  // error: 'Foo::Bar': 2 overloads have similar conversions
  foo1.Bar(true, "xx", "xx", 2, 2);
}

I don't understand why there is an ambiguity in the second case.

Aucun commentaire:

Enregistrer un commentaire