tuple: add type mapping template

This commit is contained in:
Danny Robson 2015-04-21 14:19:56 +10:00
parent 199be3213a
commit 33401becbd
2 changed files with 59 additions and 4 deletions

View File

@ -4,6 +4,12 @@
#include <typeindex>
template <typename T>
struct int_mapper
{
typedef int type;
};
int
main ()
{
@ -14,7 +20,7 @@ main ()
std::vector<int> expected {{ 1, 2, 3, 4 }};
std::vector<int> actual;
util::for_each ([&actual] (auto i) { actual.push_back (i); }, tuple);
util::tuple::for_each ([&actual] (auto i) { actual.push_back (i); }, tuple);
tap.expect_eq (actual, expected, "value iteration");
}
@ -29,10 +35,20 @@ main ()
};
std::vector<std::type_index> actual;
util::for_type<decltype(tuple)> ([&actual] (auto i) {
util::tuple::for_type<decltype(tuple)> ([&actual] (auto i) {
actual.push_back (typeid (typename decltype(i)::type));
});
tap.expect_eq (actual, expected, "type iteration");
}
{
using tuple_t = std::tuple<float>;
using mapped_t = typename util::tuple::map<tuple_t, int_mapper>::type;
bool tuple = std::is_same<typename std::tuple_element<0, tuple_t >::type, int>::value;
bool mapped = std::is_same<typename std::tuple_element<0, mapped_t>::type, int>::value;
tap.expect (!tuple && mapped, "tuple type mapping");
}
}

View File

@ -18,12 +18,13 @@
#define __UTIL_TUPLE_HPP
#include "types.hpp"
#include "variadic.hpp"
#include <tuple>
#include <type_traits>
namespace util {
namespace util { namespace tuple {
///////////////////////////////////////////////////////////////////////////
/// call a provided object with type_tag<T> for each type in a tuple
template <
@ -94,7 +95,45 @@ namespace util {
f (std::get<S> (t));
for_each<S+1,F,T...> (f, t);
}
}
///////////////////////////////////////////////////////////////////////////////
/// Statically map the member types of a tuple via F<>::type
///
/// T: tuple type
/// F: type mapping object, conversion uses F<>::type
/// I: tuple indexing helper
template <
typename T,
template <
typename
> class F,
typename I = typename make_indices<
std::tuple_size<T>::value
>::type
>
struct map;
//-----------------------------------------------------------------------------
template <
typename T,
template <
typename
> class F,
size_t ...I
>
struct map<
T,
F,
indices<I...>
> {
typedef std::tuple<
typename F<
typename std::tuple_element<I, T>::type
>::type...
> type;
};
} }
#endif