Paul Paul - 2 months ago 23
C++ Question

typesafe typedef in C++

I would like to use something like typedef in my C++ programs to enhance type safety.

As an example, suppose I have two functions

void function1(unsigned idOfType1);
void function2(unsigned idOfType2);


then I can mistakenly pass idOfType2 to function1 and vice versa. I want the compiler to give me an error in this case. I am aware that I could wrap these unsigned in a struct, but then I'd have to give provide a field name and use
.
to access them, which is slightly inconvenient. Is there a good way around this?

Edit: As far as I know
typedef
will not work for this purpose as it is just a shorthand for a type and will not be used for type checking.

Answer

As you say, a typedef won't help you here. I can't think of a better way immediately, however if you go with your wrapping in a struct/class option you could use a conversion operator to eliminate the member method or function call.

For example:

struct WrappedType
{
    operator type()
    {
         return _value;
    }

    type _value;  
}

I'm not saying this is the way to do it mind you ;-)