How to carry out self_composeN(func)(x) if func has a deduced template value that needs to be changed every time? What is an example of this? Here I've written rotate_tuple which rotates all the components of a given tuple to the left by N. I want to apply it multiple times (I know that I can just multiply N by whatever to achieve this, but I want to know the generic solution to this, because there will be other such functions that will not have such a short cut). Here is my code for rotate_tuple, which has been thoroughly tested (and it extracts the resulting type too). You need not worry about the details, I don't think, except maybe for struct rotate_tuple itself, which is quite short.
#include <tuple>
#include <string>
#include <functional>
template <int NUM_LEFT, int SHIFT>
class rotate_tuple_helper {
private:
static constexpr int positiveModulo (int i, int n) {return (i % n + n) % n;}
template <typename TUPLE>
static constexpr int shift() {return positiveModulo (SHIFT, std::tuple_size<TUPLE>::value);}
public:
template <typename TUPLE>
auto operator() (const TUPLE& t) const -> decltype (std::tuple_cat (std::make_tuple (std::get<shift<TUPLE>()>(t)), rotate_tuple_helper<NUM_LEFT-1, SHIFT+1>()(t))) {
return std::tuple_cat (std::make_tuple (std::get<shift<TUPLE>()>(t)), rotate_tuple_helper<NUM_LEFT-1, SHIFT+1>()(t));
}
};
template <int SHIFT>
class rotate_tuple_helper<0, SHIFT> {
public:
template <typename TUPLE>
std::tuple<> operator() (const TUPLE& t) const {return std::tuple<>();}
};
template <typename TUPLE, int SHIFT>
struct rotate_tuple_type {
using type = decltype (rotate_tuple_helper<std::tuple_size<TUPLE>::value, SHIFT>()(std::declval<TUPLE>()));
};
template <int SHIFT>
struct rotate_tuple {
template <typename TUPLE>
typename rotate_tuple_type<TUPLE, SHIFT>::type operator() (const TUPLE& t) const {
return rotate_tuple_helper<std::tuple_size<TUPLE>::value, SHIFT>()(t);
}
};
int main() {
using tuple_type = std::tuple<int, std::string, double, char, std::string, int, double, char>;
const tuple_type t (8, "house", 3.14, 'b', "apple", 6, 1.5, '!');
using rotate_tuple_type = rotate_tuple_type<tuple_type, 3>::type;
const rotate_tuple_type result = rotate_tuple<3>()(t); //(b, apple, 6, 1.5, !, 8, house, 3.14)
}
Anyways, I want to carry out something to the effect of self_compose<10>(rotate_tuple<3>())(t); (without using the short-cut of changing 3 to 30). Can someone help here? The example found at function composition in C++ / C++11 doesn't quite work here because it is actually not the same function being reused. The deduced template value T for rotate_tuple<3>() keeps changing (because the resulting tuple type keeps changing), and hence we don't actually have self composition. So I guess self_compose is not a good name, say self_repeat. Anyways, any idea on how to write self_repeat (generic solution that is not specific to rotate_tuple)?