c++ - 为什么功能不明确?

标签 c++

在 g++ (v4.7.3) 上编译示例代码时,出现错误:

$ g++ -std=c++11 te2b.cc
te2b.cc: In function ‘int main(int, char**)’:
te2b.cc:17:19: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
te2b.cc:10:6: note: candidate 1: void notify(std::string, int)
te2b.cc:7:6: note: candidate 2: void notify(const char*, ...)

以下是示例代码。不明白为什么会出现歧义:编译器应该知道将 main() 中对 notify() 的调用映射到第一个声明。 void notify(const char *fmt, ...)

#include <vector>
#include <iostream>
#include <unordered_map>
#include <stdarg.h>
using namespace std;
char notifyBuf[0x100000] = "\x06\x00\x00\x00" "notify""s";
void notify(const char *fmt, ...) {
    //....
}
void notify(string s, int maxSize = 0) {
    if (maxSize && (maxSize < s.size())) {
        s.erase(maxSize);
    }
    notify("%s\n", s.c_str());
}
int main(int argc, char *argv[]) {
    notify("%5d ", 89);    
    return 0;
}

有什么想法吗?谢谢。

最佳答案

§ 13.3.3 [over.match.best]/p2:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

(1.3) — for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, [...]

给定函数调用 notify("%5d ", 89); 和两个重载:

void notify(const char*, ...);   // F1
void notify(std::string, int);   // F2

对于 F1 的参数,编译器有以下一组隐式转换序列:

  • ICS0(F1) - 标准转换序列(数组到指针的转换)
  • ICS1(F1) - 省略号转换序列

F2 参数的隐式转换序列集如下:

  • ICS0(F2) - 用户定义的转换序列(通过构造函数)
  • ICS1(F2) - 标准转换序列(恒等式转换)

因为 ICS0(F1) 优于 ICS0(F2),但反过来,ICS1(F2)优于 ICS1(F1),编译器无法在两者之间进行选择。*


* § 13.3.3.2 [over.ics.rank]/p2:

When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1):

— a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

— a user-defined conversion sequence (13.3.3.1.2) is a better conversion sequence than an ellipsis conversion sequence (13.3.3.1.3).

关于c++ - 为什么功能不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442699/

相关文章:

c++ - 返回 C++ 对象 - 最佳实践

c++ - 64 位中指针和整数的模板重载问题

c++ - Qt 代码问题一般可能与 C++ 有关

c++ - 为什么 nullptr_t 不是关键字

c++ - 从需要多个输入的 C++ 源代码运行程序

c++ - 返回值 1.#INF000

c++ - 数百个空闲线程的影响

c++ - 将数据从 .cpp 文件传递​​到 Objective c ViewController

c++ - 关于 C++ OOP 数组成员复制行为

c# - 如何将非托管对话框设置为 WinForm 窗体的所有者?