Jump to content
  • Advertisement
Sign in to follow this  
Servant of the Lord

Disabling implicit conversions in typedefs?

This topic is 2409 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

If I have a struct:
struct Point
int x;
int y;

And I typedef it:
typedef Point ScreenPoint;
typedef Point WorldPoint;

Is there anyway to disable the 'WorldPoint' to 'ScreenPoint' implicit conversion?

I want to enforce having to convert through a function, to minimize errors (if math is needed to convert from ScreenPoint to WorldPoint for example).
ScreenPoint mousePos = GetMousePos();
WorldPoint positionInWorld = mousePos; //Error!

//Should be:
WorldPoint positionInWorld = ScreenToWorld(mousePos);

I find the number of conversions between units in my project to be getting a little out of hand, and I'm trying to enforce a more rigid conversion.
I could basically copy and paste a 'Point'-like class three times, and rename them, and provide conversion functions, but I was wondering if there was some way I could just typedef 'Point', and provide stand-alone functions for conversion.

If I typedef them, however, wouldn't I have implicit conversions to worry about? (Point to ScreenPoint, or Point to WorldPoint, or more serious, ScreenPoint to WorldPoint?).

Share this post

Link to post
Share on other sites
Not possible, I'm afraid. To the compiler, typedefs don't really introduce new types.

EDIT: You _could_ derive both WorldPoint and ScreenPoint from Point.

Share this post

Link to post
Share on other sites
Not that I recommend doing this, but you can make a template to wrap a type, and then combine it with a macro to manufacture more isolating typedefs:
#include <iostream>

template <typename Data, typename Token>
struct Wrapper {
Data data;
explicit Wrapper(Data data) : data(data) { }
operator Data() {
return data;

#define Wrap(WrapperName, Underlying) struct WrapperName##_WrapToken; \
typedef Wrapper<Underlying, WrapperName##_WrapToken> WrapperName

Wrap(Foo, int);
Wrap(Bar, int);

int main() {
Foo foo(5);
std::cout << foo << '\n';
Bar bar(4);
std::cout << bar << '\n';
foo = bar; // Error: no known conversion

Share this post

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!