Why doesn't the compiler perform a type conversion?

后端 未结 1 1097
春和景丽
春和景丽 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<class charT, class traits, class Allocator>
        bool operator< (const basic_string<charT,traits,Allocator>& lhs,
                const basic_string<charT,traits,Allocator>& rhs);
      template<class charT, class traits, class Allocator>
        bool operator< (const basic_string<charT,traits,Allocator>& lhs,
                const charT* rhs);
      template<class charT, class traits, class Allocator>
        bool operator< (const charT* lhs,
                const basic_string<charT,traits,Allocator>& 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 T>
    class String
    {
    };
    
    template <class T>
    bool operator< (const String<T>&, const String<T>&) { return true; }
    
    
    //if a suitable non-template function is available, it can be picked
    //bool operator< (const String<char>&, const String<char>&) { return true; }
    
    struct SimpleStruct
    {
       operator String<char> () { return value; }
       String<char> value;
    };
    
    int main()
    {
        String<char> s;
        SimpleStruct ss;
        s < ss; //the call doesn't match the function template, leaving only the commented-out candidate
    }
    
    0 讨论(0)
提交回复
热议问题