简体   繁体   English

为什么这个对重载函数的调用不明确?

[英]Why is this call to the overloaded function ambiguous?

Consider this program-考虑这个程序-

#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)});
}

On compilation, I am hitting into these errors-在编译时,我遇到了这些错误-

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) {
      |      ^~~

I understand that std::string has a constructor overload that takes in an initializer_list like so-我知道std::string有一个构造函数重载,它接受一个initializer_list像这样-

basic_string( std::initializer_list<char> ilist,
              const Allocator& alloc = Allocator() );

and std::vector<std::string> has an overload that looks like so-std::vector<std::string>有一个看起来像这样的重载-

vector( std::initializer_list<std::string> init,
        const Allocator& alloc = Allocator() );

So, it is clear that these 2 methods differ in their types.因此,很明显这两种方法的类型不同。 One takes in an initializer_list of char and the other of type std::string .一个接受charinitializer_list ,另一个接受std::string类型。

In my code when I am passing an initializer list of strings cos I pass 2 iterators to a set of strings.在我的代码中,当我传递字符串的初始值设定项列表时,我将 2 个迭代器传递给一组字符串。

Even then, why does the compiler flag this as an ambiguous call?即便如此,为什么编译器会将此标记为不明确的调用?

The compiler sees an ambiguous call to the following two constructors (note that neither of them take an initializer list):编译器发现对以下两个构造函数的调用不明确(注意它们都没有初始化列表):

template <class InputIt>
std::vector::vector (InputIt first, InputIt last, const Allocator& alloc = Allocator());

and

template <class InputIt>
std::string::string (InputIt first, InputIt last, const Allocator& alloc = Allocator());

Now, if you were to actually call the std::string constructor with those iterator arguments you'd get an error, because they don't dereference to a char.现在,如果您要使用这些迭代器参数实际调用std::string构造函数,则会出现错误,因为它们没有取消对字符的引用。 But since that check is not part of the function declaration (eg via SFINAE), you're getting the ambiguity error instead.但是由于该检查不是函数声明的一部分(例如,通过 SFINAE),因此您会收到歧义错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM