Creating new types in C++

user905122 picture user905122 · Aug 22, 2011 · Viewed 7.7k times · Source

Using typedef in C++ creates an alias for a type.

So:

typedef double Length;
typedef double Mass;

creates two aliases which can be intermixed. In other words we can pass a value of type Mass to a function that expects a value of type Length.

Is there a lightweight way of creating new types? I would like them to be double underneath but be "different" so that one can't be used in place of another.

I would prefer something lighter than creating a new class or struct. Also, I am aware of the dimensions lib in boost. This is more complex and does a lot more than I need.

Answer

Billy ONeal picture Billy ONeal · Aug 22, 2011

BOOST_STRONG_TYPEDEF seems to be designed exactly for what you're looking for. I believe it does it's magic by creating a class and overloading the operators to make it behave like a builtin type, but I've not looked at it's implementation.