constructing an object and passing it by reference

Started by
23 comments, last by stylin 18 years, 3 months ago
If you are using two ints, there wouldn't be an ambiguity (since the basic op requires no cast, but the numeric op requires two). However, if you have both a numeric and an int, both the basic and numeric op require one cast, and create an ambiguity.

And, depending on the situation, I find myself wanting one or the other: transform an integer into a time format for equality comparison (instead of the reverse), and transform a fixed-points base 10 currency into an integer (instead of the reverse).

Advertisement
Ho-humm. I should have elaborated that I was speaking about the cases the original poster asked about, namely numeric OP int and int OP numeric. Those will be ambiguous if all you have is operator OP (numeric, numeric). Sorry I wasn't more clear about it. int OP int and numeric OP numeric will of course be kosher.

Anyway, in general, if there's even a slightest danger of confusion or ambiguity, you should use explicit conversions, and preferably almost everywhere else, too.
Ok, I'll try and find out how VC++8 differs from the Standard in this regard. Here is my test code. This behaviour is wrong, then (Mixed-operands are sent to our foo operator)?

#include <iostream>struct foo {   foo( int i ) : in( i ) {}   int in;};bool operator < ( const foo & lhs, const foo & rhs ) {   std::cout << "( foo < foo ) : ";   return lhs.in < rhs.in;}int main() {   if( foo(69) < foo(420) )      std::cout << "compared foos" << std::endl;   if( 69 < 420 )      std::cout << "compared ints" << std::endl;   if( foo(69) < 420 )      std::cout << "compared foo & int" << std::endl;   if( 69 < foo(420) )      std::cout << "compared int & foo" << std::endl;   return 0;}


edit: Ahh, just read your last post ToohrVyk. I see what you mean by mind-reading now. It's not standard, but I've usually tried to reserved the lhs type as the dominant one, along with a nice, in-function comment.
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid
No, that's not ambiguous. It should compile, and each of those comparisons, except the second one, should call operator < (foo, foo).

It's when you add an foo::operator int() that the latter two will become ambiguous; both of them are then exactly one conversion apart from both operator < (int, int) and operator < (foo, foo).
True - which is why I usually choose explicit "get" functions over conversion operators.
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid

This topic is closed to new replies.

Advertisement