Enforcing type of function arguments in C++ -
i try achieve function gets passed parameters simple (e.g. std::string) cannot permuted.
imagine 2 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) trying prevent }
as can see 1 can mix order of function parameters - try prevent.
my first thought kind of typedef, e.g.
typedef std::string firstname; typedef std::string lastname; void showfullname(firstname firstname, lastname lastname) //...
but (at gnu's) c++ compiler not behave want ;)
does have solutions this?
a compiler can't read mind , know string holds name , string holds surname (they don't speak english, afterall). 2 std::string
objects interchangeable far compiler concerned (and typedef
creates alias type, not new type).
you can encapsulate strings in custom classes:
struct name { std::string str; }; struct lastname { std::string str; }; void showfullname(name name, lastname lastname) { /* ... */ }
Comments
Post a Comment