考虑这个程序-
#include <string>
#include <vector>
#include <set>
void fun(const std::string& val) {
}
void fun(std::vector<std::string> val) {
}
int main()
{
std::set<std::string> example;
fun({std::begin(example), std::end(example)});
}
在编译时,我遇到了这些错误-
prog.cc: In function 'int main()':
prog.cc:13:49: error: call of overloaded 'fun(<brace-enclosed initializer list>)' is ambiguous
13 | fun({std::begin(example), std::end(example)});
| ^
prog.cc:4:6: note: candidate: 'void fun(const string&)'
4 | void fun(const std::string& val) {
| ^~~
prog.cc:7:6: note: candidate: 'void fun(std::vector<std::__cxx11::basic_string<char> >)'
7 | void fun(std::vector<std::string> val) {
| ^~~
据我了解,std::string
它的构造函数重载会initializer_list
像这样-
basic_string( std::initializer_list<char> ilist,
const Allocator& alloc = Allocator() );
并且std::vector<std::string>
有一个看起来像这样的过载
vector( std::initializer_list<std::string> init,
const Allocator& alloc = Allocator() );
因此,很明显,这两种方法的类型不同。一个采用一个initializer_list
of char
,另一个采用type std::string
。
在我的代码中,当我传递字符串cos的初始化列表时,我将2个迭代器传递给一组字符串。
即使这样,编译器为何仍将此标记为歧义调用?
编译器看到对以下两个构造函数的模棱两可的调用(请注意,它们都不使用初始化列表):
template <class InputIt>
std::vector::vector (InputIt first, InputIt last, const Allocator& alloc = Allocator());
和
template <class InputIt>
std::string::string (InputIt first, InputIt last, const Allocator& alloc = Allocator());
现在,如果您实际上要std::string
使用那些迭代器参数调用构造函数,则会收到错误消息,因为它们没有取消引用char。但是由于该检查不是函数声明的一部分(例如,通过SFINAE),所以您将得到歧义错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句