WaeCo
WaeCo

Reputation: 1217

overloaded operator deduction using user-defined conversions in c++11

My problem may be related to http://en.cppreference.com/w/cpp/language/overload_resolution#Call_to_an_overloaded_operator. But in my case I have const complex types:

class Complex {
public:
   int data;

   Complex(int i) : data(i) {}
   bool operator < (const Complex& other) const { return data < other.data; }
};
class Holder {
public:
    Complex data;

    Holder(int i) : data(i) {}
    operator const Complex&() const { return data; }
};
//...
Holder a(1), b(2);
assert(a < b); //Error 

Compiler error in g++ 4.9: no match for ‘operator<’ (operand types are ‘Holder‘ and ‘Holder‘)

Any idear how to fix this?

Btw. I need that conversion to only allow casts to const types.

Upvotes: 1

Views: 42

Answers (2)

Simon Kraemer
Simon Kraemer

Reputation: 5670

a < b is equivalent to a.operator<(b).

a is of type Holder and doesn't have a function named operator<.

A function call to a member function doesn't trigger an implicit conversion from Holder to Complex.

If you cast a to const Complex& manually your function will work:

assert(((const Complex&)a) < b);

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65600

Member comparison operators do not allow for implicit conversions on the left hand side, you need to make your operator a non-member function:

class Complex {
public:
   int data;

   Complex(int i) : data(i) {}
};

bool operator < (const Complex& lhs, const Complex& rhs) 
{ return lhs.data < rhs.data; }

Live Demo

Upvotes: 4

Related Questions