Unclear use of operator double()

后端 未结 3 1898
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 09:34

I have a Rectangle class with conversion operators to both double and std::string:

class Rectangle
{
public:
    Rectangle         


        
相关标签:
3条回答
  • 2021-02-07 10:03

    Since you did not provide an operator<< overload for Rectangle, the compiler considers other overloads for which the arguments can be converted to the parameter types.

    If any of the overloads are templates, then template argument substitution happens to them before overload resolution. The compiler tries to deduce the template parameters from the types of the arguments supplied to the function.

    The string overload is not considered because of a template argument substitution failure:

    template <class CharT, class Traits, class Allocator>
    std::basic_ostream<CharT, Traits>&
        operator<<(std::basic_ostream<CharT, Traits>& os,
                   const std::basic_string<CharT, Traits, Allocator>& str);
    

    Template argument substitution does not consider user-defined conversions, so the compiler can't deduce the types CharT, Traits, or Allocator from the type Rectangle, so this overload does not participate in overload resolution. (Recall that std::string is just a typedef of std::basic_string<char, std::char_traits<char>, std::allocator<char>>.)

    Therefore there is one overload of operator<< which is a better match than any other, and that is the double overload. Not a template, but a member function of a class template.

    basic_ostream<CharT, Traits>& basic_ostream<CharT, Traits>::operator<<(double);
    
    0 讨论(0)
  • 2021-02-07 10:19

    There is nothing special about double-overloading than other primitive types overloadings. In this case, it is the only primitive overload available. The compiler will behave the same for int, char, etc..

    Notice that if we would have more than one primitive type overload the compiler will throw

    error: ambiguous overload for 'operator<<' ...
    
    0 讨论(0)
  • 2021-02-07 10:28

    You do not have an operator to output the rectangle to the stream. cout does have an overload that takes a double and your class can be implicitly converted to a double so that is chosen.

    The reason the string overload is not selected and is not considered as an ambiguity is because operator << for a string is a member function and is not included in the member overload and non member overload set of cout. If we comment out the operator double we can see we get a compiler error.

    If we want to have the operator string called then we would need to explicitly cast r into a string. Live Example

    0 讨论(0)
提交回复
热议问题