Skip to content

Instantly share code, notes, and snippets.

@eiennohito
Last active August 29, 2015 14:22
Show Gist options
  • Save eiennohito/f173ac360aab6720391d to your computer and use it in GitHub Desktop.
Save eiennohito/f173ac360aab6720391d to your computer and use it in GitHub Desktop.
#include <tuple>
#include <vector>
#include <type_traits>
#include <iostream>
template<int cnt, typename X, typename T0, typename ...T>
struct index_of0 {
enum {
value = std::is_same<X, T0>::value ? cnt : index_of0<cnt + 1, X, T...>::value
};
};
template<int cnt, typename X, typename T0>
struct index_of0<cnt, X, T0> {
enum {
value = std::is_same<X, T0>::value ? cnt : -1
};
};
template<typename X, typename ...T>
struct index_of {
enum {
value = index_of0<0, X, T...>::value
};
};
template <typename Fn, int i, typename T, bool end>
struct for_each0
{
void operator()(Fn fn, T& t) {
fn(std::get<i>(t));
for_each0<Fn, i + 1, T, std::tuple_size<T>::value == (i + 1)>()(fn, t);
}
};
template <typename Fn, int i, typename T>
struct for_each0<Fn, i, T, true>
{
void operator()(Fn fn, T& v) {
//do nothing in the end case
}
};
template <typename ...T>
class holder {
typedef std::tuple<std::vector<T>...> tuple_t;
tuple_t inner_;
public:
template<typename Tp>
std::vector<Tp>& vec() {
return std::get<index_of<Tp, T...>::value>(inner_);
}
//should be a functor with template operator ()
template <typename Fn>
void for_each(Fn fn) {
for_each0<Fn, 0, tuple_t, (0 == std::tuple_size<tuple_t>::value)>()(fn, inner_);
}
};
using namespace std;
int main(int argc, char const *argv[])
{
holder<int, double> h;
h.vec<int>().push_back(0);
h.vec<double>().push_back(0.0);
h.for_each([](auto& x) { cout << x.size() << " "; });
holder<float> h2;
h2.vec<float>().push_back(3);
h2.vec<float>().push_back(4);
h2.for_each([](auto& x) { cout << x.size() << "floats "; } );
cout << h.vec<int>().size() << " " << h.vec<double>().size() << endl;
/* code */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment