以下程序编译正常并按预期工作。它的输出是:
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
参数更改为 bool
和 foo1.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, 2
与 const char*, ...
匹配时,第一个参数的转换序列具有完全匹配rank,第二到第四个是省略号转换序列。所以(完全匹配,省略号,省略号,省略号)。
当您将 "Test", "xx", 1, 2
与 bool, const char*, ...
匹配时,第一个参数的第一个转换序列有转换等级;第二个是完全匹配,第三个和第四个是省略号转换序列。换句话说,(转换、精确匹配、省略号、省略号)。
精确匹配胜过转换;一切都胜过省略号(参见 [over.ics.rank] )。因此,我们这里有一种所谓的交叉情况,其中一个函数对一个参数有更好的转换序列,而另一个函数对另一个参数有更好的转换序列。由于一个函数优于另一个函数的必要(但不充分)条件是没有一个转换序列比另一个函数([over.match.best]/1)差,所以这两个函数都不比另一个好。
关于c++ - 重载、可变参数函数和 bool 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856131/