Suppose I have written generic map functions for STL tuples(tuple, pair), as well as STL sequences (vector, list, deque). Now I want to write a global map function calling the appropriate special functions given the input types.
I have something along the lines of
template <typename... Ts>
struct mappable {
static constexpr bool is_instance = false;
};
template <typename... Tuples, typename = require<all<is_stl_tuple, Tuples...>::value>>
struct mappable<Tuples...> {
template <typename Func>
auto map(Func&& f, Tuples&&... ts) {
return tuple::map(std::forward<Func>(f), ts...);
}
static constexpr bool is_instance = true;
};
template <typename... Sequences, typename = require<all<is_stl_sequence, Sequences...>::value>>
struct mappable<Sequences...> {
template <typename Func>
auto map(Func&& f, Sequences&&... seqs) {
return sequence::map(std::forward<Func>(f), seqs...);
}
static constexpr bool is_instance = true;
};
template <typename Func, typename... Ts>
auto map(Func&& f, Ts&&... ts) {
static_assert(mappable<Ts...>::is_instance, "Tried calling map on unsupported types. Mappable arguments must be supplied.");
return mappable<Ts...>::map(std::forward<Func>(f), std::forward<Ts>(ts)...);
}
Although hopefully self-explanatory the type-checking function defs:
// true iff Unary<Ts>::value... == true for at least one Ts
template <template <typename> class Unary, typename... Ts>
struct any;
// true iff Unary<Ts>::value... == true for all Ts
template <template <typename> class Unary, typename... Ts>
struct all;
template <bool B>
using require = typename std::enable_if<B>::type;
Obviously this won't (and does not) work since I specialize mappable on the default arguments. Is there any way to do this and if not (and I have to redesign), how would you go about redesigning those functions? sequence::map shall for example take any combination of stl sequences, so all ideas I have about restructuring just shift the problem elsewhere...
Thanks in advance for any help...
Edit: As requested here are usage examples (actually my test code for it) before I started doing the above:
auto t0 = std::make_tuple(2.f, -5, 1);
auto t1 = std::make_tuple(1, 2);
auto b0 = tuple::map([] (auto v) { return v > decltype(v)(0); }, t0);
auto r0 = tuple::map([] (auto v0, auto v1) { return v0 + v1; }, t0, t1);
// b0 is tuple<bool, bool, bool>(true, false, true)
// b1 is tuple<float, int>(3.f, -3)
and for sequences:
std::vector<float> s0 = {1.f, 2.f, 3.f, 0.f};
std::list<int> s1 = {3, 0, -2};
auto r = sq::map([] (auto v0, auto v1) { return v0 + v1; }, s0, s1);
// type of r is compound type of first argument (vector here), result is
// vector<float>(4.f, 2.f, 1.f)
Implementations of these map functions are completely different - the aim of my approach above is to be able to drop the namespace and just use map having it doing The Right Thing.