Why doesn't the compiler perform a type conversion?

后端 未结 1 1099
春和景丽
春和景丽 2020-12-31 13:00

Consider the following code.

#include 
#include 

struct SimpleStruct
{
    operator std::string () { return value; }
    std::         


        
1条回答
  •  天命终不由人
    2020-12-31 13:57

    operator< for std::string is a function template. The overloads are:

      template
        bool operator< (const basic_string& lhs,
                const basic_string& rhs);
      template
        bool operator< (const basic_string& lhs,
                const charT* rhs);
      template
        bool operator< (const charT* lhs,
                const basic_string& rhs);
    

    Your call doesn't match any of the available overloads, so they are all removed from a list of candidates. Since no function template was picked as a candidate for resolving the call, there is nothing to convert SimpleStruct to.

    template 
    class String
    {
    };
    
    template 
    bool operator< (const String&, const String&) { return true; }
    
    
    //if a suitable non-template function is available, it can be picked
    //bool operator< (const String&, const String&) { return true; }
    
    struct SimpleStruct
    {
       operator String () { return value; }
       String value;
    };
    
    int main()
    {
        String s;
        SimpleStruct ss;
        s < ss; //the call doesn't match the function template, leaving only the commented-out candidate
    }
    

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