Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a TR1 tuple

Being stuck in TR1 land, for a test program I need to perform certain operations on a number of objects of specific types. I have a couple of tuple type definitions which look like this:

typedef std::tr1::tuple< bool
                       , signed char
                       , signed short
                       , signed int
                       , signed long long
                       , unsigned char
                       , unsigned short
                       , unsigned int
                       , unsigned long long >  integral_types;

From each tuple type an object is to be created. I then have function templates similar to this:

template<typename T>
void invoke_operation_1(T& obj);

These need to be called for all objects in a tuple object.

How do I do that in C++03?

like image 918
sbi Avatar asked May 03 '13 13:05

sbi


1 Answers

There was a feature just finalized in Bristol for C++14 to address this very problem. It's not too hard to deal with.

For the simpler case, you can use a recursive template. It's a smidge of a mess though without partial function specialization and such.

template<typename Tup, std::size_t N> struct visit_detail {
     template<typename F> static void call(Tup& t, F f) {
         f(std::tr1::get<N>(t));
         return visit_detail<Tup, N+1>::call(t, f);
     }
};
template<typename Tup> struct visit_detail<Tup, std::tr1::tuple_size<Tup>::value> {
    template<typename F> static void call(Tup& t, F f) {}
}

template<typename Tup, typename F> void visit(Tup& t, F f) {
    return visit_detail<Tup, 0>::call(t, f);
}

Here f can be hardcoded or a parameter function object or whatever you want.

like image 149
Puppy Avatar answered Sep 18 '22 15:09

Puppy