Enforcing type of function arguments in C++

285 Views Asked by At

I try to achieve that a function gets passed some parameters that are all simple (e.g. std::string) but cannot be permuted.

Imagine two functions like

void showFullName(std::string firstname, std::string lastname) {
    cout << "Hello " << firstname << " " << lastname << endl;
}

void someOtherFunction() {
    std::string a("John");
    std::string b("Doe");

    showFullName(a, b); // (1) OK
    showFullName(b, a); // (2) I am trying to prevent this
}

As you can see one can mix the order of function parameters - which is what I try to prevent.

My first thought was some kind of typedef, e.g.

typedef std::string Firstname;
typedef std::string Lastname;

void showFullName(Firstname firstname, Lastname lastname)
//...

but (at most GNU's) c++ compiler does not behave as I want ;)

Does someone have a good solutions for this?

1

There are 1 best solutions below

1
On

A compiler can't read your mind and know which string holds a name and which string holds a surname (they don't speak english, afterall). Two std::string objects are interchangeable as far compiler is concerned (and a typedef just creates an alias for a type, not a new type).

You can encapsulate the strings in custom classes:

struct Name {
    std::string str;
};

struct Lastname {
    std::string str;
};

void showFullName(Name name, Lastname lastname) { /* ... */ }