Sign in to follow this  
Storyyeller

implicit conversion from float to char

Recommended Posts

So I have several overloaded functions.
    //function bodies omitted for brevity
    template <class T>
    inline void Debug(T message, char endc = '\n')
    inline void Debug(bool message, char endc = '\n')
    inline void Debug(double d1, double d2, char endc='\n')

I tried to call it with a pair of floats, and expected to get the last one. Much to my surprise, GCC complained that it was ambiguous because the first is also a candidate with t = float. How is it possible to implicitly convert a float to a char? Is C++ just weird like that?

Share this post


Link to post
Share on other sites
Quote:
Original post by Storyyeller

How is it possible to implicitly convert a float to a char? Is C++ just weird like that?


Casting a float to an integral type will return the integer part of the float. Nothing weird about that at all. char is an integer just like int and short

Also, it's usually preferable to overload instead of specialize when you can, unlike what __fastcall suggested. I think there's a Scott Meyers item on that, but the jist is that the specific specialization to pick is only picked after the compiler decides to use the template, so if you've specialized for every type and then someone comes and writes an overload, the compiler may choose an unexpected version of the function based on these rules

Share this post


Link to post
Share on other sites
So am I correct in assuming that theoretically, it could also cast the float to an int and then to a bool to use the second function, but this option was not considered because this implicit conversion is worse then the others according to the standard?

Share this post


Link to post
Share on other sites
Quote:
Original post by Storyyeller
So am I correct in assuming that theoretically, it could also cast the float to an int and then to a bool to use the second function?

No. Only one implicit conversion can be performed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this