Consider the following code:
class C {
public:
int operator-(int x) {
return 3-x;
}
};
class wrapper {
public:
operator C() {
static C z;
return z;
}
} wrap;
int main() {
return wrap-3;
}
it gives this error on g++:
test.cpp: In function ‘int main()’:
test.cpp:17:17: error: no match for ‘operator-’ in ‘wrap - 3’
The conversion operator seems to be working because this version works:
class wrapper {
public:
operator int() {
static int z=3;
return z--;
}
} wrap;
int main() {
return wrap-3;
}
operator- also seems to be working because this code compiles:
class C {
public:
int operator-(int x) {
return 3-x;
}
};
int main() {
C c
return c-3;
}
What’s wrong with the combination of these two? Why can’t an operator be applied after implicit conversion? Are there any workarounds to this problem?
Implicit conversions aren’t performed on the first operand when a member function is matched. Just make your operator a non-member, perhaps a friend:
From [over.match.oper]: