0

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 类。

我的问题是,我可以简单而美丽地解决这个缺点吗?

4

4 回答 4

5

是的,您可以简单而漂亮地解决缺点:

为工作使用正确的工具!在这种情况下,结构或类。

在这种情况下,元组并不意味着替换结构。仅仅因为你的工具箱里有一把新的闪亮的锤子并不意味着你现在应该用它来切割木头。

于 2014-02-15T16:32:45.637 回答
4

好吧,从概念上讲tuple和普通的旧struct非常相似。主要区别在于struct使用名称访问成员,而tuple使用索引访问成员。

因此,您似乎想tuple用作结构-为什么不直接使用struct

于 2014-02-15T16:32:04.653 回答
1

您可以使用枚举来提供“字段名称”:

enum FIELDS { path, name, id, parent_id, remote_id };
auto field = make_tuple<Field>("C:\", "file.txt", 23, 20, 41);      

foo( std::get<FIELDS::path>(field) );  // may easy forget that the 0-index is path
std::get<FIELDS::name>(field) = new_name; // and  1-index is name
int id = std::get<FIELDS::id>(field);  

(编辑后,我在这里为枚举使用限定版本,因为它们是相当常见的字段名称,但这不是绝对必要的)

于 2014-02-15T16:12:39.003 回答
1

通常,您应该只使用tuple将在几行内打包和使用的数据,或者当您实际上不知道数据是什么时,除了需要将其打包在一起。有时两者兼而有之。

这使得它对于你想要打包一些参数并在以后解包它们的泛型编程非常有用。或者,如果你有一个本地 lambda,你想从中得到一个子结果并且不想为它创建一个结构——但即便如此,我也会被一个结构所吸引。

for 的一个很好的用途tuple是让您通过方法(和版本) struct返回其参数的std::tie(一个tuple引用)。为你写一个词法之类的东西,这会导致错误的实现,甚至在某些情况下(默认相等不太正确,但你想调用默认相等作为子问题)。make_tieconsttupleoperator<<===

于 2014-02-15T20:17:43.397 回答