Как я могу иметь неявные операторы преобразования как в строку, так и в int?
Упрощенный код:
#include <iostream>
#include <string>
struct Value
{
operator std::string() const { return "abc"; }
operator int() const { return 42; }
};
int main() {
Value v;
std::string s;
s = v; // error here
// lines below not really needed
int i;
i = v;
std::cout << s << " " << i << "\n";
}
c ++ 11 или более поздняя версия. Это ошибки, сообщаемые в строке назначения строки.
sandbox/casting_main.cpp: In function ‘int main()’:
sandbox/casting_main.cpp:14:7: error: ambiguous overload for ‘operator=’ (operand types are ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ and ‘Value’)
s = v; // error here
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/bits/locale_classes.h:40,
from /usr/include/c++/5/bits/ios_base.h:41,
from /usr/include/c++/5/ios:42,
from /usr/include/c++/5/ostream:38,
from /usr/include/c++/5/iostream:39,
from sandbox/casting_main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:550: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)
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/bits/locale_classes.h:40,
from /usr/include/c++/5/bits/ios_base.h:41,
from /usr/include/c++/5/ios:42,
from /usr/include/c++/5/ostream:38,
from /usr/include/c++/5/iostream:39,
from sandbox/casting_main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:569: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)
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/bits/locale_classes.h:40,
from /usr/include/c++/5/bits/ios_base.h:41,
from /usr/include/c++/5/ios:42,
from /usr/include/c++/5/ostream:38,
from /usr/include/c++/5/iostream:39,
from sandbox/casting_main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:587: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 ++ 11 есть оператор присваивания basic_string:
basic_string& operator=(charT c);
Этот оператор присваивания вызывает неоднозначность, которую компилятор не может разрешить.
Есть ли способ иметь неявные операторы преобразования в строку и int в одном классе?