6

When I write code like this:

struct foo {
    operator int() const { return 1; }
};
int main() {
    foo a, b;
    auto tmp = (a < b);
}

it works, but while I write code like this:

struct foo {
    operator string() const { return string("foo"); }
};
int main() {
    foo a, b;
    auto tmp = (a < b);
}

Compiler(clang++) says that error: invalid operands to binary expression ('foo' and 'foo')

I wonder why, as both string type and int type have comparison operators, but when foo has a user defined int conversion, it will implicit convert to int to compare, however when foo only has a user defined string conversion, compiler doesn't do implicit conversion though (string)a<(string)b works well.

6
  • 1
    I dont know the rule that causes this, but most likely it has something to do with int being a built in type Commented Feb 20, 2017 at 12:09
  • 4
    related/dupe: stackoverflow.com/questions/42252023/… Commented Feb 20, 2017 at 12:34
  • @NathanOliver imho question isnt really a dupe, but the answer pefectly explains also this one Commented Feb 20, 2017 at 12:36
  • @tobi303 Yeah, that is why I did not close it myself. Not sure if it should be closed as a dupe or not but the answer does explain the problem. Commented Feb 20, 2017 at 12:38
  • Possible duplicate of Implicit conversion operator priority Commented Feb 20, 2017 at 12:45

1 Answer 1

1

I think the problem is that string is not a basic type. std::string is a specialization of a template, specifically std::basic_string<char>

So operator < is defined as

template <class CharT, class Traits, class Allocator>
    bool operator< (const std::basic_string<CharT, Traits, Allocator> &_Left,  const std::basic_string<CharT, Traits, Allocator> &_Right);

It will work with:

auto tmp = (static_cast<std::string>(a) < static_cast<std::string>(b));

Then operator < becomes:

bool std::operator< <char, std::char_traits<char>, std::allocator<char>>(const std::string &_Left, const std::string &_Right)
Sign up to request clarification or add additional context in comments.

1 Comment

And because user defined conversion are not considered for template function specialization. See this related answer: [stackoverflow.com/questions/42252023/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.