Search code examples
c++type-safety

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)

Solution

  • 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.