我有以下示例代码。它可以在 clang 上编译,但不能在 Visual Studio 2013 上编译。
#include <iostream>
#include <utility>
#include <string>
using namespace std;
void f(const pair<string, string>& p)
{
cout << p.first << ", " << p.second << endl;
}
void f(initializer_list<pair<string, string> > ps) {
for (auto p : ps) f(p);
}
int main()
{
f({ "2", "3" });
f({ { "2", "3" }, { "3", "4" } });
}
对 f 的第二次调用无法编译:
1error C2668: 'f' : ambiguous call to overloaded function
could be 'void f(std::initializer_list<std::pair<std::string,std::string>>)'
or 'void f(const std::pair<std::string,std::string> &)'
1> while trying to match the argument list '(initializer-list)'
如果我使用成对的 int 而不是成对的字符串,它确实可以正常工作。
有人知道 Visual Studio 中存在这样的问题吗?还是我做错了什么?
谢谢。
最佳答案
{ { "2", "3" }, { "3", "4" } }
可用于初始化 initializer_list<pair<string, string> >
或pair<string, string>
,在第二种情况下,通过调用 std::string
的双迭代器构造函数(并在此过程中引起UB)。两者都是列表初始化序列。两者都调用用户定义的转换。
§13.3.3.2 [over.ics.rank]/p3:
List-initialization sequence L1 is a better conversion sequence than list-initialization sequence L2 if:
- L1 converts to
std::initializer_list<X>
for someX
and L2 does not [...]
没有任何歧义。 void f(initializer_list<pair<string, string> > ps);
应明确选择。
关于c++ - 在VS2013中使用initializer_list对函数的不明确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26168013/