C ++: using type safety to distinguish between binary argument types

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

How can I use type safety so that the compiler warns me or makes an error if I call a function with the wrong sequence of arguments (all arguments are int)?

I tried typedefs: Typedef does not run any warnings or compiler errors:

typedef int X; typedef int Y; void foo(X,Y); X x; Y y; foo(y,x); // compiled without warning) 
+8
c ++ type-safety
source share
3 answers

You will have to create wrapper classes. Suppose you have two different units (for example, seconds and minutes), both of which are represented as int. You will need something like the following:

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

and a similar class in seconds. An explicit constructor prevents accidental use of an int as a Minute , but the conversion operator allows you to use a Minute int anywhere.

+12
source share

typedef creates type aliases. As you have discovered, there is no security.

One possibility, depending on what you are trying to achieve, is to use enum . This is also not too typical, but it is closer. For example, you cannot pass int to an enumeration parameter without casting it.

+4
source share

Receive a note with a message. Write in capital letters "X FIRST! THEN Y!" Attach it to your computer screen. I honestly don't know what else to advise. The use of wrapper classes is certainly too great when the problem can be solved with post-it and a magic marker.

-5
source share

Source: https://habr.com/ru/post/650992/


All Articles