Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new types in C++

Tags:

c++

typedef

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.

like image 383
user905122 Avatar asked Aug 22 '11 01:08

user905122


People also ask

Does typedef create a new type?

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.

What is typedef declaration in C?

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.

What is typedef in C with example?

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.

Does C have typedef?

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.


2 Answers

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.

like image 189
Billy ONeal Avatar answered Sep 19 '22 22:09

Billy ONeal


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.

like image 29
Ken Bloom Avatar answered Sep 19 '22 22:09

Ken Bloom