Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef type checking?

Tags:

c++

types

typedef

How do I get g++ to make type checks on typedefs? Is it possible? i.e.

typedef int T1;
typedef int T2;

T1 x = 5;     //Ok with me
T2 y = x;     //Any way to get an error or a warning here?

I can't use C++0x features (I don't know whether they can do this.)

EDIT: What I want is something like this:

typedef int BallID;
typedef int BatID;

BatID x = 10;
map<BatID, Bat*> m;
m.insert(make_pair(x, bigbat));        //OK
BallID y = 15;
m.insert(make_pair(y, smallbat));     //Give me a warning at least plz

Is this too much to ask?

like image 822
nakiya Avatar asked Feb 23 '11 18:02

nakiya


3 Answers

Consider using a strong typedef: https://www.boost.org/doc/libs/release/boost/serialization/strong_typedef.hpp

like image 95
Edward Strange Avatar answered Sep 29 '22 19:09

Edward Strange


To expand upon Nawaz's answer: when you typedef A B, then B is just an alias for A, not a separate type. x and y are just int's in your example.

If you want to create a new type, use a one-member struct.

like image 43
Fred Foo Avatar answered Sep 29 '22 20:09

Fred Foo


As long as T1 and T2 are typedefs of same type, you will not get any warning!

like image 43
Nawaz Avatar answered Sep 29 '22 18:09

Nawaz