【发布时间】:2014-02-15 16:05:10
【问题描述】:
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 类。
我的问题是,我能简单又漂亮地解决这个缺点吗?
【问题讨论】:
-
您可以使用
enum类型来指定索引并使内容更具可读性。 -
这正是您应该不在这种情况下使用元组的原因!
-
你解决了什么问题/使用 tuples 代替结构有什么好处?
-
是的,你可以很好地解决这个问题overloading the dot operator。简单!
-
请不要使用这样的元组。