Reputation: 1095
I'm writing wrapper classes for basic types so they can be typed... except I've run into a problem. I need both these methods to make it nice:
Integer32(FastInteger32 value);
Boolean operator>(Integer32 value);
operator FastInteger32();
Except when I go to use the '>' operator between a 'FastInteger' and an 'Integer', the compiler sees two possible routes to go and doesn't just pick one, it blows up. Is there a way to to tell it to just pick one?
The entire code:
typedef unsigned int FastInteger32;
class Integer32
{
public:
Integer32(FastInteger32 value);
Boolean operator>(Integer32 value);
operator FastInteger32();
private:
FastInteger32 value;
};
int main()
{
Integer32 a = 5;
FastInteger32 b = 5;
if (a < b) { } // Doesn't know what to do here, convert b to Integer32 and compare or convert a to FastInteger32 and compare
}
You guys rock by the way, thanks for helping!
Upvotes: 1
Views: 2142
Reputation: 180135
C++ will always prefer an overload which doesn't have a conversion at all. Therefore, adding bool operator<(FastInteger32, Integer32)
and bool operator<(Integer32, FastInteger32)
will eliminate all ambiguities.
Upvotes: 1
Reputation: 4207
The problem is with your constructor (Integer32(FastInteger32 value);
). Single argument constructors should (nearly) always be declared as explicit
. Simply change the declaration to explicit Integer32(FastInteger32 value);
; the definition should not change.
Upvotes: 1