开发者

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

开发者 https://www.devze.com 2023-02-04 02:12 出处:网络
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.

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 开发者_如何学Cwith 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)


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.


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.


Get a post-it note. Write on it, in big letters, "X FIRST! THEN Y!" Stick it to your computer screen. I honestly don't know what else to advise. Using wrapper classes is surely overkill, when the problem can be solved with a post-it and a magic marker.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号