我认为主要动机是std::tuple
按位置寻址不是很易读,也不是很健壮;从理由:
假设我们有一个函数 get_employee_info 以元组的形式返回一些员工信息。说诸如 get<2>(get_employee_info(...) 之类的内容并不能真正表明我们正在寻找员工的办公室。此外,如果我们稍后对返回另一个员工属性感兴趣,我们可能需要调整索引整个节目。
当然,这只能对独特的类型进行。但是,可以使用例如枚举类、轻量级包装器等std::string
,以使这些更易于阅读和维护。
这是一个简单的例子:
#include <tuple>
#include <string>
#include <iostream>
struct FirstName : std::string { using std::string::basic_string; };
struct LastName : std::string { using std::string::basic_string; };
struct EmployeeID
{
EmployeeID(int id) : employeeID_m(id) { }
operator int() const { return employeeID_m; }
const EmployeeID &operator=(int id) { employeeID_m = id; return *this; }
int employeeID_m;
};
using Record = std::tuple<FirstName, LastName, EmployeeID>;
void printRecord(const Record &r)
{
std::cout << std::get<FirstName>(r) << " "
<< std::get<LastName>(r)
<< "'s employee ID is "
<< std::get<EmployeeID>(r)
<< std::endl;
}
int main() {
Record record1 = std::make_tuple(FirstName("Slim"), LastName("Jim"), EmployeeID(12233));
Record record2 = std::make_tuple(FirstName("Big"), LastName("Bill"), EmployeeID(33221));
printRecord(record1);
printRecord(record2);
return 0;
}
带输出:
Slim Jim's employee ID is 12233
Big Bill's employee ID is 33221