views:

119

answers:

4

How can I resolve the ambiguous call between these two in C++?

Color(int, int, int)
Color(float, float, float)

It is both ambiguous when the values are hardcoded i.e. Color(1, 2, 3) and when they are variables Color(r, g, b). Why wouldn't the compiler resolve according to data type? In variable form?

EDIT: Sorry, too much C++ makes me forget there's a other languages. And there is not much "full code" that was all about it.

float x, y, z;
int r, g, b;
Color(1, 2, 3); // ambiguous
Color(1.0, 2.0, 3.0); // ambiguous
Color(r, g, b); // ambiguous  <--- this one is a real pain
Color((int)r, (int)g, (int)b); // ambiguous
Color(x, y, z); //OK
Color(1u, 2u, 3u); //OK
Color(1.0f, 2.0f, 3.0f); //OK
A: 

Depending on the language, but you can probably cast them, if you are using C# or C++.

e.g. for C#:
Color((int)r, (int)g, (int)b)
or
Color((float)r, (float)g, (float)b)

Billism
+6  A: 

The problem seems to be that you have declared

Color(unsigned, unsigned, unsigned);
Color(float, float, float);

ie, all three args must be either float or unsigned. If you try to call it with other types (such as int or double), its ambiguous -- the compiler doesn't know which you want as both are just a good (or as bad if you prefer). You could improve things a bit by declaring more overloads:

Color(int, int, int);
Color(double, double, double);

but you'd still get ambiguity errors if try to call it with mixed types.

Chris Dodd
wow that's right. that's how i become dumb when intellisense is not working. sorry about that.
Jake
A: 

Given your test cases, particularly Color(r,g,b), I'd bet you don't have Color(int, int, int), but Color(unsigned int, unsigned int, unsigned int). That's why you're getting ambiguous calls that you're not expecting.

miked
+1  A: 

The type of a floating-point literal is double, not float. In general, you should be using double unless you have a specific reason for using float, such as needing to consume less memory. As other answers have mentioned, you seem to have declared:

Color(unsigned int, unsigned int, unsigned int);
Color(float, float, float);

Which means that invoking, e.g., Color(int, int, int) has two possible conversions, neither of which is preferred. You can fix this by declaring:

Color(int, int, int);
Color(double, double, double);

Instead, and performing any conversions you need within the class itself, or invoking the constructor as:

Color((unsigned int)r, (unsigned int)g, (unsigned int)b);
Jon Purdy