Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to explicitly call Myclass::operator string() with std::string::operator+()?

Tags:

c++

Consider the code below. I don't understand why my GCC compiler does not try to implicitly use Myclass::operator string(), although Myclass::operator string() is defined:

#include <string>

using namespace std;

struct T {
};

T operator+(const T& a, const T&b) { }

struct Myclass {
    operator string() const { }
    operator T() const { }
};

int main() {
    T a;
    string b;
    Myclass c;
    c + a;  // OK
    c.operator  string() + b; // OK
    c + b; // Not OK
    /* The above line does not compile, although in <string> I see:
    basic_string<_CharT, _Traits, _Alloc>
    operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
          const basic_string<_CharT, _Traits, _Alloc>& __rhs)
     */
}
like image 453
Martin Avatar asked Nov 04 '22 02:11

Martin


1 Answers

Because the string operator is a template, it cannot be picked up whereas the other operator can.

like image 122
Puppy Avatar answered Nov 10 '22 19:11

Puppy