C++ Variadic Template Array / Accessing Elements
In C++, how would I be able to access elements of a variadic template like an array? I have made a basic attempt to show what I am trying to acheive below, but, of course, it doesn't compile:
template<class... Args> struct Apple{
public:
Apple(Args... A) : V(A){}
Apple() : p(0){}
void push_back(decltype(V[p]) v){
V[p++] = v;
}
private:
Args... V;
int p;
};
int main(){
Apple<int, double> a(5, 6.5);
Apple<int, double> b;
b.push_back(5);
b.push_back(6.5);
}
I'd suggest you take a look at variadic template. The typename... Ts
is not an array. So you can't expect Args... v
to be expanded as an array. Besides, how will you create an array with each element of different type?
Your requirement is quite similiar what the std::tuple
provides, you should take a look at its implementation.
Take a look at this GoingNative 2012 video given by Andrei. It's a great introduction to variadic template.
And here is one of my toy tuple
when play with variadic template. There's some duplication with what C++11 stl provided, but its a toy any way.
#include <iostream>
#include <vector>
#include <typeinfo>
#include <type_traits>
using namespace std;
template <typename T, typename... Ts> class MyTuple : public MyTuple<Ts...> {
using base = MyTuple<Ts...>;
public:
T elem;
MyTuple(T v, Ts... vs) : base(vs...), elem(v) {}
};
template <typename T> class MyTuple<T> {
public:
T elem;
MyTuple(T v) : elem(v) {}
};
template <int i, typename T, typename... Ts> struct type_of {
static_assert(i < sizeof...(Ts) + 1, "index out of range");
typedef typename type_of<i - 1, Ts...>::type type;
};
template <typename T, typename... Ts> struct type_of<0, T, Ts...> {
typedef T type;
};
template <int i, typename T, typename... Ts>
typename enable_if<i == 0, typename type_of<i, T, Ts...>::type&>::type get(MyTuple<T, Ts...> &t) {
static_assert(i >= 0, "index out of range");
static_assert(i < sizeof...(Ts) + 1, "index out of range");
return t.elem;
}
template <int i, typename T, typename... Ts>
typename enable_if<i != 0, typename type_of<i, T, Ts...>::type&>::type get(MyTuple<T, Ts...> &t) {
static_assert(i >= 0, "index out of range");
static_assert(i < sizeof...(Ts) + 1, "index out of range");
MyTuple<Ts...>& base = t;
return get<i - 1>(base);
}
int main(int argc, char const *argv[]) {
cout << typeid(type_of<0, int, char, long>::type).name() << endl; // print i
cout << typeid(type_of<1, int, char, long>::type).name() << endl; // print c
cout << typeid(type_of<2, int, char, long>::type).name() << endl; // print l
MyTuple<int, int> t(0, 1);
cout << get<0>(t) << endl;
cout << get<1>(t) << endl;
return 0;
}