C++11 添加了非常有用的容器 std::tuple,现在我可以将许多结构转换为 std::tuple :
// my Field class
struct Field
{
std::string path;
std::string name;
int id;
int parent_id;
int remote_id;
};
//create
Field field = {"C:/", "file.txt", 23, 20, 41 };
//usage
foo( field.path );
field.name= new_name;
int id = field.id;
至
//to std::tuple, /--path, /--name /--id, /--parend_id, /--remote_id
using Field = std::tuple< std::string, std::string , int, int , int >;
//create
auto field = make_tuple<Field>("C:\", "file.txt", 23, 20, 41);
// usage
foo( std::get<0>(field) ); // may easy forget that the 0-index is path
std::get<1>(field) = new_name; // and 1-index is name
int id = std::get<2>(field); // and 2-index is id, also if I replace it to 3,
//I give `parent_id` instead of `id`, but compiler nothing say about.
但是,这只是在大型项目中使用 std::tuple 的一个缺点——可能很容易忘记每种元组的含义,因为这里不是按名称访问,只能按索引访问。
出于这个原因,我会使用旧的 Field 类。
我的问题是,我可以简单而美丽地解决这个缺点吗?