Unclear use of operator double()

后端 未结 3 1904
伪装坚强ぢ
伪装坚强ぢ 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 
    std::basic_ostream&
        operator<<(std::basic_ostream& os,
                   const std::basic_string& 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, std::allocator>.)

    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& basic_ostream::operator<<(double);
    

提交回复
热议问题