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.
Syntax. Note that a typedef declaration does not create types. It creates synonyms for existing types, or names for types that could be specified in other ways.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
typedef is used to define new data type names to make a program more readable to the programmer. For example: | main() | main() { | { int money; | typedef int Pounds; money = 2; | Pounds money = 2 } | } These examples are EXACTLY the same to the compiler.
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
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.
While BOOST_STRONG_TYPEDEF is a pretty simple solution, if you're mixing lengths and masses into more complicated units (e.g. in the physical sciences) then you might want to use Boost.Units.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With