Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't char* implicitly converted to std::string?

Tags:

c++

Here is my code:

#include <iostream>
using namespace std;

struct ST {};

bool operator==(const struct ST *s1, const string &s2) {
    return true;
}

int main() {
    struct ST *st = new ST();
    const char *p = "abc";

    if (st == p) {
        return 0;
    }

    return 1;
}

I get compile error:

prog.cpp:14:12: error: comparison between distinct pointer types ‘ST*’ and ‘const char*’ lacks a cast [-fpermissive]
  if (st == p) {
            ^

I wonder why the implicit conversion from char* to string does not work here?

UPDATE Anton's answer makes sense, I updated the code:

#include <string>
using namespace std;

struct ST {};

bool operator==(const struct ST s1, const string &s2) {
    return true;
}

int main() {
    struct ST st;
    const char *p = "abc";

    if (st == p) {
        return 0;
    }

    return 1;
}

Now it compiles.

like image 866
my_question Avatar asked Sep 03 '14 15:09

my_question


1 Answers

§13.3.1.2 Operators in expressions [over.match.oper] states:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

This is exactly your case: operator=='s arguments are pointers, so it's considered to be built-in and compiler doesn't look for possible overloads.

like image 89
Anton Savin Avatar answered Oct 04 '22 14:10

Anton Savin