Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: using type safety to distinguish types oftwo int arguments

I have various functions with two int arguments (I write both the functions and the calling code myself). I am afraid to confuse the order of argument in some calls.

How can I use type safety to have compiler warn me or error me if I call a function with wrong sequence of arguments (all arguments are int) ?

I tried typedefs: Typedef do not trigger any compiler warnings or errors:

typedef int X; typedef int Y; 

void foo(X,Y); 

X x; Y y; 

foo(y,x); // compiled without warning)
like image 602
Andrei Avatar asked Jan 12 '11 19:01

Andrei


2 Answers

You will have to create wrapper classes. Lets say you have two different units (say, seconds and minutes), both of which are represented as ints. You would need something like the following to be completely typesafe:

class Minute
{
public:
    explicit Minute(int m) : myMinute(m) {}
    operator int () const { return myMinute; }

private:
    int myMinute;
};

and a similar class for seconds. The explicit constructor prevents you accidentally using an int as a Minute, but the conversion operator allows you to use a Minute anywhere you need an int.

like image 188
Daniel Gallagher Avatar answered Nov 07 '22 21:11

Daniel Gallagher


typedef creates type aliases. As you've discovered, there's no type safety there.

One possibility, depending on what you're trying to achieve, is to use enum. That's not fully typesafe either, but it's closer. For example, you can't pass an int to an enum parameter without casting it.

like image 23
Fred Larson Avatar answered Nov 07 '22 21:11

Fred Larson