与隐式转换相关的歧义的 c++ 编译失败

问题描述 投票:0回答:1

尝试编译以下代码。

#include <string>

#include <boost/any.hpp>


class V
{
public:
   V& operator=(int i)
   {
      v = i;
      return *this;
   }
   V& operator=(const std::string& s)
   {
      v = s;
      return *this;
   }
   operator int() const
   {
      return boost::any_cast<int>(v);
   }
   operator std::string() const
   {
      return boost::any_cast<std::string>(v);
   }
private:
   boost::any v;
};


int main()
{
   V v;
   std::string s1 = "hello", s2;
   v = s1;
   s2 = v;
}

以下是错误。

$ g++ test__boost_any.cpp
test__boost_any.cpp: In function ‘int main()’:
test__boost_any.cpp:37:9: error: ambiguous overload for ‘operator=’ (operand types are ‘std::__cxx11::string’ {aka ‘std::__cxx11::basic_string<char>’} and ‘V’)
    s2 = v;
         ^
In file included from /usr/include/c++/8/string:52,
                 from test__boost_any.cpp:1:
/usr/include/c++/8/bits/basic_string.h:668:7: note: candidate: ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
       operator=(const basic_string& __str)
       ^~~~~~~~
/usr/include/c++/8/bits/basic_string.h:718:7: note: candidate: ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
       operator=(_CharT __c)
       ^~~~~~~~
/usr/include/c++/8/bits/basic_string.h:736:7: note: candidate: ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
       operator=(basic_string&& __str)
       ^~~~~~~~
c++ operator-keyword boost-any
1个回答
0
投票

由于您使用的是转换运算符,因此这里有两个“用户定义的转换序列”在起作用。两者的排名都不比另一个高。消除歧义的唯一方法是执行转换为所需的类型: s2 = static_cast<std::string>(v);

© www.soinside.com 2019 - 2024. All rights reserved.