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 を使用する場合の欠点が 1 つだけあります。タプルの各タイプの意味を簡単に忘れてしまう可能性があります。これは、名前ではなく、インデックスのみでアクセスするためです。
そのため、古い Field クラスを使用します。
私の質問は、この欠点をシンプルかつ美しく解決できるかということです。