简体   繁体   中英

function overload based on typedef defined similar types

I have the below class for cards, i want to check the validation of input based on the card_type or card_value. Both are of same types in the program but logically different.

Is it a good way to validate this way? But in any case what i want is not supported by C++ as both are of same types. How can i do this other way?

typedef int type;
typedef int number;

struct card {
    type card_type;
    number card_number;
    card(int t, int n) : card_type(t), card_number(n) { 
        check(card_type);
        check(card_number);
    }

    bool check(const type& t)
    {
        if (t >= 4) {
            cout << "Card Type is not valid " << endl;
            return false;
        }
        return true;
    }

    bool check(const number& n)
    {
        return false;
    }
};

Obviously i am getting the error ambiguous function overload.

Since you use "type" I guess you have a small number of types, so I would use enum like so

enum  type {A,B};
.
.
.
    card(int t, int n) : card_type((type)t), card_number(n)


     int main()
     {
        type x = A  ;
        number y = 5;
        struct card my_card(1,2);
        my_card.check(x);
        my_card.check(y);
        return 0;
     }

Another "hackish" solution I used is this:

typedef unsigned int type;
typedef int number;

Use strong type, then you don't have to check

enum class CardColor {Heart, Spade, Diamond, Club};
enum class CardValue {Ace, Two, Three, /*...*/, Queen, King};

struct Card {
    CardColor color;
    CardValue value;
};

and then

Card card{CardColor::Club, CardValue::Ace};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM