Use meaningful words to get tuple elements
c++, c++11, templates, tuples
Solution
There is discussion underway:
- n3584 Wording for accessing Tuplefields by type
- on the isocpp forums https://groups.google.com/a/isocpp.org/forum/?hl=en&fromgroups=#!topic/std-proposals/N-kIXNrkTUk
Right now, you can use tagged elements with something like Fusion Map:
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/at_key.hpp>
using namespace boost::fusion;
typedef map<
pair<struct what_t1_means, int>
, pair<struct what_t2_means, int> >
map_type;
int main()
{
map_type m { 42, -42 };
auto i1 = at_key<what_t1_means>(m);
auto i2 = at_key<what_t2_means>(m);
}
I opted to use `int` twice, to highlight that the 'key types' are separate from the 'tuple' types.
See it live on http://liveworkspace.org/code/4CxV4T$0
Problem
For example, I have a tuple like ``` std::tuple<T0, T1, T2> tp; ``` I can get its element by `std::get()` function like ``` auto e0 = std::get<0>(tp); ``` I prefer to using meaningful index to access the element other than the number. A way to do it is to define an enum like ``` enum MyEnum { WHAT_T0_MEANS = 0, WHAT_T1_MEANS = 1, WHAT_T2_MEANS = 2 }; ``` Thus I can use a friendly version of get like ``` auto e0 = std::get<WHAT_T0_MEANS>(tp); ``` The problem is that sometimes I find the order of types in the tuple is not friendly and change it to like `std::tuple<T1, T0, T2>`. But it is so easy to forget to change the order of elements in the enum. A good way may be to define what T0 means in the class T0 or use map to find what T0 means, or else. And then write some function to get the elements through what T0 means. Any way to do it? Here the what T0 means are not necessary to by enum elements. It can be a type or anything else. If T0, T1, and T2 are different types. A function like ``` T MyGet<T>(tp) ``` where T can be T0, T1 or T2, is okay.