考虑以下:
struct A {
A(int, int) { }
};
struct B {
B(A ) { } // (1)
explicit B(int, int ) { } // (2)
};
int main() {
B paren({1, 2}); // (3)
B brace{1, 2}; // (4)
}
Run Code Online (Sandbox Code Playgroud)
建设brace中(4)清楚明确地调用(2).在铛,施工paren中(3)明确要求(1),其中作为GCC 5.2,它失败编译:
main.cpp: In function 'int main()':
main.cpp:11:19: error: call of overloaded 'B(<brace-enclosed initializer list>)' is ambiguous
B paren({1, 2});
^
main.cpp:6:5: note: candidate: B::B(A)
B(A ) …Run Code Online (Sandbox Code Playgroud) 我真的不明白这一点,我认为编译器首先执行大括号中的内容然后将结果赋予最合适的函数.这看起来它给函数一个初始化列表来处理它...
#include <string>
#include <vector>
using namespace std;
void func(vector<string> v) { }
void func(vector<wstring> v) { }
int main() {
func({"apple", "banana"});
}
Run Code Online (Sandbox Code Playgroud)
错误:
<stdin>: In function 'int main()':
<stdin>:11:27: error: call of overloaded 'func(<brace-enclosed initializer list>)' is ambiguous
<stdin>:11:27: note: candidates are:
<stdin>:6:6: note: void func(std::vector<std::basic_string<char> >)
<stdin>:8:6: note: void func(std::vector<std::basic_string<wchar_t> >)
Run Code Online (Sandbox Code Playgroud)
为什么不func(vector<string> v)调用我的超载,我可以这样做吗?