c++ - 重载、可变参数函数和 bool 类型

标签 c++ c++11

以下程序编译正常并按预期工作。它的输出是:

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);
}

现在,如果我将第二个 Bar 函数的 int 参数更改为 boolfoo1.Bar(1, "xx ", "xx", 2, 2);foo1.Bar(true, "xx", "xx", 2, 2);,那么下面一行就不会编译后出现错误:'Foo::Bar': 2 overloads have similar conversions:

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

未编译的整个程序:

#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);
}

我不明白为什么第二种情况有歧义。

编辑

但是如果指针隐式转换为bool,为什么下面会编译?

#include <stdio.h>

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

int main()
{
  Foo foo1;
  foo1.Bar("Test");
  foo1.Bar(true);
}

最佳答案

当您将 "Test", "xx", 1, 2const char*, ... 匹配时,第一个参数的转换序列具有完全匹配rank,第二到第四个是省略号转换序列。所以(完全匹配,省略号,省略号,省略号)。

当您将 "Test", "xx", 1, 2bool, const char*, ... 匹配时,第一个参数的第一个转换序列有转换等级;第二个是完全匹配,第三个和第四个是省略号转换序列。换句话说,(转换、精确匹配、省略号、省略号)。

精确匹配胜过转换;一切都胜过省略号(参见 [over.ics.rank] )。因此,我们这里有一种所谓的交叉情况,其中一个函数对一个参数有更好的转换序列,而另一个函数对另一个参数有更好的转换序列。由于一个函数优于另一个函数的必要(但不充分)条件是没有一个转换序列比另一个函数([over.match.best]/1)差,所以这两个函数都不比另一个好。

关于c++ - 重载、可变参数函数和 bool 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856131/

相关文章:

c++ - 模板化运算符 << 未被识别

c++ - 为什么编译器在存在模板化构造函数时生成复制/移动构造函数?

c++ - 调用模板类构造函数

c++ - Variadic模板继承,成员函数重载

c++ - 在 C++ 模板中将变量作为参数传递

c++11:为什么没有将 "auto&"推断为正确的类型?

c++ - 在 C++ 中通过 libxml2 解析部分 XML 时过滤掉 namespace 错误

c++ - 禁用 __LINE__ 宏?

c++ - 努力使用链表实现 Set

c++ - 如何解决 lint 错误 "Reference initialization causes loss of const/volatile integrity"