Color(int, int, int) vs Color(float, float, float) ambiguous call

拜拜、爱过 提交于 2019-12-10 18:18:11

问题


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

回答1:


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.




回答2:


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);



回答3:


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.




回答4:


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)



来源:https://stackoverflow.com/questions/3909406/colorint-int-int-vs-colorfloat-float-float-ambiguous-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!