0

我试图实现一个函数被传递一些简单的参数(例如std :: string)但不能被置换。

想象两个函数,比如

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
}

如您所见,可以混合函数参数的顺序——这是我试图阻止的。

我的第一个想法是某种 typedef,例如

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

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

但是(至多 GNU 的)c++ 编译器的行为不像我想要的那样;)

有人对此有很好的解决方案吗?

4

1 回答 1

2

编译器无法读懂您的想法并知道哪个字符串包含名称以及哪个字符串包含姓氏(毕竟他们不会说英语)。std::string就编译器而言,两个对象是可互换的(并且typedef只是为类型创建别名,而不是新类型)。

您可以将字符串封装在自定义类中:

struct Name {
    std::string str;
};

struct Lastname {
    std::string str;
};

void showFullName(Name name, Lastname lastname) { /* ... */ }
于 2014-03-25T09:37:47.540 回答