Creating tuples from tuples

Let's say that you have a tuple and you want to create a new tuple by applying a metafunction for each type of the first. What is the "most efficient C ++ metafanization to accomplish this task? Is it possible to use the C ++ 0x variational pattern to provide a better implementation?

+5
source share
1 answer

How to do it:

template<typename Metafun, typename Tuple>
struct mod;

// using a meta-function class
template<typename Metafun, template<typename...> class Tuple, typename ...Types>
struct mod<Metafun, Tuple<Types...>> {
  typedef Tuple<typename Metafun::template apply<Types>::type...>
    type;
};

Then

typedef std::tuple<int, bool> tuple_foo;

struct add_pointer {
  template<typename T>
  struct apply { typedef T *type; };
};

typedef mod<add_pointer, tuple_foo>::type tuple_ptrfoo;

This is the use of the metafunction class by packaging applyin a non-template. This allows you to pass it to C ++ 03 templates (which cannot accept templates with arbitrary parameters, just by doing template<typename...> class X). You can, of course, accept a pure metafound (not a class) too

template<template<typename...> class Metafun, typename Tuple>
struct mod;

// using a meta-function
template<template<typename...> class Metafun, template<typename...> class Tuple, 
         typename ...Types>
struct mod<Metafun, Tuple<Types...>> {
  typedef Tuple<typename Metafun<Types>::type...>
    type;
};

And use the template std::add_pointer

typedef mod<std::add_pointer, tuple_foo>::type tuple_ptrfoo;

,

// transforming a meta function into a meta function class
template<template<typename...> class Metafun>
struct ToClass {
  template<typename ... T>
  struct apply { typedef Metafun<T...> type; };
};

typedef mod<ToClass<std::add_pointer>, tuple_foo>::type tuple_ptrfoo;

, .

+8

All Articles