• Advertisement
Sign in to follow this  

Implicit cast to bool

This topic is 1920 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

What is the reasoning behind disallowing implicit value casts to bool? Is there a better way to do the same thing?

I'm looking to be able to do something like this:


Keystate@ state = keyboard.getKeystate("space");

// elsewhere...
if (state)
{
// key is down
}

Share this post


Link to post
Share on other sites
Advertisement
The reasoning is that the implicit conversion to bool in C/C++ is a very common bug with less experienced programmers.

Why not add a function, e.g. isDown() to the Keystate object? It would make the code more readable to those unfamiliar with it.


Keystate@ state = keyboard.getKeystate("space");
// elsewhere...
if ( state.isDown() )
{
// key is down
}

Share this post


Link to post
Share on other sites
That's probably the best solution in this case, and it is definitely more readable. I was hoping to use implicit bool casting for other purposes, but I think the limitation might actually help me write idiomatic code.

Share this post


Link to post
Share on other sites
I support Andreas Jonsson, he right!
I used to not like this code:


SomeClassPtr @p;

if( p !is null )
{
}


but then I realized that so immediately clear!
For scripts this is best way.smile.png

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement