45

C++11 tuples are nice, but they have two huge disadvantages to me, accessing members by index is

  1. unreadable
  2. difficult to maintain (if I add an element in the middle of the tuple, I'm screwed)

In essence what I want to achieve is this

tagged_tuple <name, std::string, age, int, email, std::string> get_record (); {/*...*/}
// And then soomewhere else

std::cout << "Age: " << get_record().get <age> () << std::endl;

Something similar (type tagging) is implemented in boost::property_map, but I ca'nt get my head around how to implement it in a tuple with arbitary number of elements

PS Please do not suggest defining an enum with tuple element indices.

UPD OK, here is a motivation. In my projects I need to be able to define lots of different tuples 'on-the-fly' and all of them need to have certain common functions and operators. This is not possible to achieve with structs

UPD2 Actually my example is probably a bit unrealistic to implement. How about this?

tagged_tuple <tag<name, std::string>, tag<age, int>, tag<email, std::string>> get_record (); {/*...*/}
// And then somewhere else

std::cout << "Age: " << get_record().get <age> () << std::endl;
23
  • 4
    What is your objection to using enum? Oct 25, 2012 at 9:07
  • 39
    It's called a struct?
    – Pubby
    Oct 25, 2012 at 9:08
  • 5
    @aleguna: if you don't need any tuple functionality then I'd say use struct {std::string name, int age, std::string email} get_record();. You could name the return type, but in C++11 it's not really necessary since it can be captured with auto or decltype. Oct 25, 2012 at 9:16
  • 5
    You can almost certainly define all the common operations you need using function templates, defined outside of any particular class but within the namespace containing these classes. These can be specialised for each class if necessary. Oct 25, 2012 at 9:22
  • 9
    Fair enough. I wish C++ would let you iterate over the elements of a struct at compile-time using template metaprogramming. Since std::pair and std::tuple already allow this, it must be possible to design the language do this for ordinary structs too, and if that were the case then we wouldn't need special tuple types in the first place. Oct 25, 2012 at 9:42

8 Answers 8

57

I'm not aware of any existing class that does this, but it's fairly easy to throw something together using a std::tuple and an indexing typelist:

#include <tuple>
#include <iostream>

template<typename... Ts> struct typelist {
  template<typename T> using prepend = typelist<T, Ts...>;
};

template<typename T, typename... Ts> struct index;
template<typename T, typename... Ts> struct index<T, T, Ts...>:
  std::integral_constant<int, 0> {};
template<typename T, typename U, typename... Ts> struct index<T, U, Ts...>:
  std::integral_constant<int, index<T, Ts...>::value + 1> {};

template<int n, typename... Ts> struct nth_impl;
template<typename T, typename... Ts> struct nth_impl<0, T, Ts...> {
  using type = T; };
template<int n, typename T, typename... Ts> struct nth_impl<n, T, Ts...> {
  using type = typename nth_impl<n - 1, Ts...>::type; };
template<int n, typename... Ts> using nth = typename nth_impl<n, Ts...>::type;

template<int n, int m, typename... Ts> struct extract_impl;
template<int n, int m, typename T, typename... Ts>
struct extract_impl<n, m, T, Ts...>: extract_impl<n, m - 1, Ts...> {};
template<int n, typename T, typename... Ts>
struct extract_impl<n, 0, T, Ts...> { using types = typename
  extract_impl<n, n - 1, Ts...>::types::template prepend<T>; };
template<int n, int m> struct extract_impl<n, m> {
  using types = typelist<>; };
template<int n, int m, typename... Ts> using extract = typename
  extract_impl<n, m, Ts...>::types;

template<typename S, typename T> struct tt_impl;
template<typename... Ss, typename... Ts>
struct tt_impl<typelist<Ss...>, typelist<Ts...>>:
  public std::tuple<Ts...> {
  template<typename... Args> tt_impl(Args &&...args):
    std::tuple<Ts...>(std::forward<Args>(args)...) {}
  template<typename S> nth<index<S, Ss...>::value, Ts...> get() {
    return std::get<index<S, Ss...>::value>(*this); }
};
template<typename... Ts> struct tagged_tuple:
  tt_impl<extract<2, 0, Ts...>, extract<2, 1, Ts...>> {
  template<typename... Args> tagged_tuple(Args &&...args):
    tt_impl<extract<2, 0, Ts...>, extract<2, 1, Ts...>>(
      std::forward<Args>(args)...) {}
};

struct name {};
struct age {};
struct email {};

tagged_tuple<name, std::string, age, int, email, std::string> get_record() {
  return { "Bob", 32, "[email protected]"};
}

int main() {
  std::cout << "Age: " << get_record().get<age>() << std::endl;
}

You'll probably want to write const and rvalue get accessors on top of the existing one.

6
  • 12
    ecatmur, you kung-fu is good, I need some time to meditate over this :)
    – user1773602
    Oct 25, 2012 at 10:20
  • +1 for creativity, but I can't actually see the benefit of creating a bunch of empty tag structs over just using an enum and the usual std::tuple. Oct 25, 2012 at 11:02
  • 15
    @j_random_hacker, benefit is that e.g. a email can have different index in different tuples. consider template <class Tuple> void print_email (const Tuple& t) {std::cout << t.get<email>();} This is not possible with index
    – user1773602
    Oct 25, 2012 at 11:12
  • 6
    While above example is fairly easy for anyone who's spent a month or two in Template Metaprogramming-land, it is not for the average pragmatic C++-developer. (This is why we hide abstractions in libraries, kids!)
    – Qqwy
    Nov 8, 2018 at 9:11
  • 3
    I take it "fairly easy" when said by you has about the same meaning as "clearly" when said by mathematicians. Jun 16, 2021 at 23:58
10

C++ does not have a struct type that can be iteratable like a tuple; it's either/or.

The closest you can get to that is through Boost.Fusion's struct adapter. This allows you to use a struct as a Fusion sequence. Of course, this also uses a series of macros, and it requires you to list the struct's members explicitly in the order you want to iterate over them. In the header (assuming you want to iterate over the struct in many translation units).

Actually my example is probably a bit unrealistic to implement. How about this?

You could implement something like that, but those identifiers need to actually be types or variables or something.

1
  • 4
    +1 for mentioning Boost.Fusion – it's immediately what came to mind when I read the OP's question.
    – ildjarn
    Oct 25, 2012 at 20:45
9

I have my own implementation to show off, wich can allow you not to declare the attributes on top of the file. A version with declared attributes exists too, but there is no need to define them, declaration is sufficient.

It is pure STL, of course, and do not use the preprocessor.

Example:

#include <named_tuples/tuple.hpp>
#include <string>
#include <iostream>
#include <vector>

namespace {
unsigned constexpr operator "" _h(const char* c,size_t) { return named_tuples::const_hash(c); }
template <unsigned Id> using at = named_tuples::attribute_init_int_placeholder<Id>;
using named_tuples::make_tuple;
}

int main() {
  auto test = make_tuple( 
      at<"nom"_h>() = std::string("Roger")
      , at<"age"_h>() = 47
      , at<"taille"_h>() = 1.92
      , at<"liste"_h>() = std::vector<int>({1,2,3})
      );

  std::cout 
    << test.at<"nom"_h>() << "\n"
    << test.at<"age"_h>() << "\n"
    << test.at<"taille"_h>() << "\n"
    << test.at<"liste"_h>().size() << std::endl;

  test.at<"nom"_h>() = "Marcel";
  ++test.get<1>();

  std::cout 
    << test.get<0>() << "\n"
    << test.get<1>() << "\n"
    << test.get<2>() << "\n"
    << test.get<3>().size() << std::endl;

  return 0;
}

Find the complete source here https://github.com/duckie/named_tuple. Feel free to read, it is quite simple.

2

The real problems you have to solve here are:

  • Are the tags mandatory or optional?
  • Are the tags unique? Is it enforced at compile time?
  • In which scope does the tag reside? Your example seems to declare the tags inside the declaring scope instead of encapsulated in the type, which might not be optimal.

ecatmur proposed a good solution; but the tags are not encapsulated and the tag declaration is somehow clumsy. C++14 will introduce tuple addressing by type, which will simplify his design and guarantee uniqueness of the tags, but not solve their scope.

Boost Fusion Map can also be used for something similar, but again, declaring the tags is not ideal.

There is a proposal for something similar on the c++ Standard Proposal forum, which would simplify the syntax by associating a name to the template parameter directly.

This link lists different ways of implementing this (including ecatmur's solution) and presents a different use-case for this syntax.

1

Here's another way to do it, it's a bit uglier to define the types but it helps prevent errors at compile time because you define the pairs with a type_pair class (much like std::map). Adding a check to make sure your keys/name are unique at compile time is the next step

Usage:

   using user_t = tagged_tuple<type_pair<struct name, std::string>, type_pair<struct age, int>>;
  // it's initialized the same way as a tuple created with the value types of the type pairs (so tuple<string, int> in this case)
  user_t user  { "chris", 21 };
  std::cout << "Name: " << get<name>(user) << std::endl;
  std::cout << "Age: " << get<age>(user) << std::endl;
 // you can still access properties via numeric indexes as if the class was defined as tuple<string, int>
  std::cout << "user[0] = " << get<0>(user) << std::endl;

I opted against having get be a member function to keep it as similar to std::tuple as possible but you could easily add one to the class. Source code here

1

Here is an implementation similar to ecatmur's answer using the brigand metaprogramming library (https://github.com/edouarda/brigand):

#include <iostream>
#include <brigand/brigand.hpp>

template<typename Members>
class TaggedTuple{

    template<typename Type>
    struct createMember{
        using type = typename Type::second_type;
    };

    using DataTuple = brigand::transform<Members, createMember<brigand::_1>>;
    using Keys = brigand::keys_as_sequence<Members, brigand::list>;
    brigand::as_tuple<DataTuple> members;

public:

    template<typename TagType>
    auto& get(){
        using index = brigand::index_of<Keys, TagType>;
        return std::get<index::value>(members);
    }
};

int main(){

    struct FloatTag{};
    struct IntTag{};
    struct DoubleTag{};

    TaggedTuple<brigand::map<
            brigand::pair<FloatTag, float>,
            brigand::pair<IntTag, int>,
            brigand::pair<DoubleTag, double>>> tagged;

    tagged.get<DoubleTag>() = 200;
    auto val = tagged.get<DoubleTag>();
    std::cout << val << std::endl;

    return 0;
}
1
0

I implemented "c++ named tuple" using boost preprocessor. Please see the Sample usage below. By deriving from tuple, I get comparison, printing, hash, serialization for free (assuming they are defined for tuple).

#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/comma_if.hpp>


#define CM_NAMED_TUPLE_ELEMS_ITR(r, xxx, index, x ) BOOST_PP_COMMA_IF(index) BOOST_PP_TUPLE_ELEM(2,0,x) 
#define CM_NAMED_TUPLE_ELEMS(seq) BOOST_PP_SEQ_FOR_EACH_I(CM_NAMED_TUPLE_ELEMS_ITR, "dum", seq)
#define CM_NAMED_TUPLE_PROPS_ITR(r, xxx, index, x) \
      BOOST_PP_TUPLE_ELEM(2,0,x) BOOST_PP_CAT(get_, BOOST_PP_TUPLE_ELEM(2,1,x))() const { return get<index>(*this); } \
      void BOOST_PP_CAT(set_, BOOST_PP_TUPLE_ELEM(2,1,x))(const BOOST_PP_TUPLE_ELEM(2,0,x)& oo) { get<index>(*this) = oo; }
#define CM_NAMED_TUPLE_PROPS(seq) BOOST_PP_SEQ_FOR_EACH_I(CM_NAMED_TUPLE_PROPS_ITR, "dum", seq)
#define cm_named_tuple(Cls, seq) struct Cls : tuple< CM_NAMED_TUPLE_ELEMS(seq)> { \
        typedef tuple<CM_NAMED_TUPLE_ELEMS(seq)> Base;                      \
        Cls() {}                                                            \
        template<class...Args> Cls(Args && ... args) : Base(args...) {}     \
        struct hash : std::hash<CM_NAMED_TUPLE_ELEMS(seq)> {};            \
        CM_NAMED_TUPLE_PROPS(seq)                                           \
        template<class Archive> void serialize(Archive & ar, arg const unsigned int version)() {                                                    \
          ar & boost::serialization::base_object<Base>(*this);                              \
        }                                                                   \
      }

//
// Example:
//
// class Sample {
//   public:
//   void do_tata() {
//     for (auto& dd : bar2_) {
//       cout << dd.get_from() << " " << dd.get_to() << dd.get_tata() << "\n";
//       dd.set_tata(dd.get_tata() * 5);
//     }
//     cout << bar1_ << bar2_ << "\n";
//   }
//
//   cm_named_tuple(Foo, ((int, from))((int, to))((double, tata)));  // Foo == tuple<int,int,double> with named get/set functions
//
//   unordered_set<Foo, Foo::hash> bar1_;
//   vector<Foo> bar2_;  
// };

Please note that code sample above assumes you have defined "generic" ostream printing functions for vector/tuple/unordered_set.

0

I have "solved" a similar problem in production code. First, I have an ordinary struct (actually a class with various member functions, but it's only the data members which we are interested in here)...

class Record
{
    std::string name;
    int age;
    std::string email;
    MYLIB_ENABLE_TUPLE(Record) // macro
};

Then just below the struct definition, but outside of any namespace, I have another macro:

MYLIB_DECLARE_TUPLE(Record, (o.name, o.age, o.email))

The disadvantage with this approach is that the member names must be listed twice, but this is the best I have been able to come up with while still permitting traditional member access syntax within the struct's own member functions. The macro appears very near the definitions of the data members themselves, so it is not too hard to keep them in sync with each other.

In another header file I have a class template:

template <class T>
class TupleConverter;

The first macro is defined so as to declare this template to be a friend of the struct, so it can access its private data members:

#define MYLIB_ENABLE_TUPLE(TYPE) friend class TupleConverter<TYPE>;

The second macro is defined so as to introduce a specialization of the template:

#define MYLIB_DECLARE_TUPLE(TYPE, MEMBERS) \
    template <>                            \
    class TupleConverter<TYPE>             \
    {                                      \
        friend class TYPE;                 \
        static auto toTuple(TYPE& o)       \
            -> decltype(std::tie MEMBERS)  \
        {                                  \
            return std::tie MEMBERS;       \
        }                                  \
    public:                                \
        static auto toTuple(TYPE const& o) \
            -> decltype(std::tie MEMBERS)  \
        {                                  \
            return std::tie MEMBERS;       \
        }                                  \
    };

This creates two overloads of the same member function name, TupleConverter<Record>::toTuple(Record const&) which is public, and TupleConverter<Record>::toTuple(Record&) which is private and accessible only to Record itself through friendship. Both return their argument converted to a tuple of references to private data members by way of std::tie. The public const overload returns a tuple of references to const, the private non-const overload returns a tuple of references to non-const.

After preprocessor substitution, both friend declarations refer to entities defined in the same header file, so there should be no chance of other code abusing the friendship to break encapsulation.

toTuple can't be a member function of Record, because its return type can't be deduced until the definition of Record is complete.

Typical usage looks like this:

// lexicographical comparison
bool operator< (Record const& a, Record const& b)
{
    return TupleConverter<Record>::toTuple(a) < TupleConverter<Record>::toTuple(b);
}

// serialization
std::ostream& operator<< (std::ostream& os, Record const& r)
{
    // requires template<class... Ts> ostream& operator<<(ostream&, tuple<Ts...>) defined elsewhere
    return os << TupleConverter<Record>::toTuple(r);
}

There are many ways this could be extended, for example by adding another member function in TupleConverter which returns a std::vector<std::string> of the names of the data members.

If I'd been allowed to use variadic macros then the solution might have been even better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.