Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <tuple>
- #include <type_traits>
- #include <utility>
- using namespace std;
- using std::forward; // You can change this if you like unreadable code or care hugely about namespace pollution.
- template<size_t N>
- struct ApplyMember
- {
- template<typename C, typename F, typename T, typename... A>
- static inline auto apply(C&& c, F&& f, T&& t, A&&... a) ->
- decltype(ApplyMember<N-1>::apply(forward<C>(c), forward<F>(f), forward<T>(t), std::get<N-1>(forward<T>(t)), forward<A>(a)...))
- {
- return ApplyMember<N-1>::apply(forward<C>(c), forward<F>(f), forward<T>(t), std::get<N-1>(forward<T>(t)), forward<A>(a)...);
- }
- };
- template<>
- struct ApplyMember<0>
- {
- template<typename C, typename F, typename T, typename... A>
- static inline auto apply(C&& c, F&& f, T&&, A&&... a) ->
- decltype((forward<C>(c)->*forward<F>(f))(forward<A>(a)...))
- {
- return (forward<C>(c)->*forward<F>(f))(forward<A>(a)...);
- }
- };
- // C is the class, F is the member function, T is the tuple.
- template<typename C, typename F, typename T>
- inline auto apply(C&& c, F&& f, T&& t) ->
- decltype(ApplyMember<std::tuple_size<typename std::decay<T>::type>::value>::apply(forward<C>(c), forward<F>(f), forward<T>(t)))
- {
- return ApplyMember<std::tuple_size<typename std::decay<T>::type>::value>::apply(forward<C>(c), forward<F>(f), forward<T>(t));
- }
- class Test
- {
- public:
- Test(){};
- ~Test(){};
- void f1(int i1 = 0) { cout << "f1: " << i1 << endl; }
- void f2(int i1 = 0, int i2 = 0) {cout << "f2: " << i1 << " " << i2 << endl;}
- };
- template<int N, typename A>
- struct caller
- {
- void operator()(A a){}
- };
- template<typename A>
- struct caller<0, A>
- {
- void operator()(A a)
- {
- Test *t = new Test();
- apply(t, &Test::f1, a);
- delete t;
- }
- };
- template<typename A>
- struct caller<1, A>
- {
- void operator()(A a)
- {
- Test *t {new Test()};
- apply(t, &Test::f2, a);
- delete t;
- }
- };
- std::tuple<
- caller<0, std::tuple<int>>,
- caller<1, std::tuple<int, int>>
- > g_call;
- template<int N, typename A>
- void call(A a)
- {
- std::get<N>(g_call)(a);
- }
- int main()
- {
- std::tuple<int> a1 {1};
- std::tuple<int, int> a2 {3,4};
- call<0>(a1);
- call<1>(a2);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment