Kristian D'Amato
Kristian D'Amato

Reputation: 4046

Implicit conversion to match operator argument

I have the following class declaration:

class DepthDescriptor
{
public:
    DepthDescriptor(DepthType depth);
    bool operator==(DepthDescriptor& type);
    bool operator>=(DepthDescriptor& type);
    bool operator<=(DepthDescriptor& type);
...
}

Why does the following line not perform an implicit conversion to the DepthDescriptor object so that the operator comparison can take place?

if (depth == Depth_8U)
{
...
}

Note that depth is a DepthDescriptor object, DepthType is an enum, and Depth_8U is one of the enum values. I was hoping that lines like the one above would first call the implicit constructor DepthDescriptor(DepthType depth) and then the appropriate operator, but I'm getting no operator "==" matches these operands.

Upvotes: 0

Views: 193

Answers (2)

john
john

Reputation: 8027

To get the conversion to happen you should write global functions not member functions, and you should be const-correct. I.e.

bool operator==(const DepthDescriptor& lhs, const DepthDescriptor& rhs)
{
    ...
}

Conversions will not happen on the left hand side if you use member functions. Conversions may not happen in a standard conformant compiler unless you are const-correct.

Upvotes: 0

qianfg
qianfg

Reputation: 898

Try

bool operator==(const DepthDescriptor& type) const;
bool operator>=(const DepthDescriptor& type) const;
bool operator<=(const DepthDescriptor& type) const;

Upvotes: 1

Related Questions