
Question:
I am trying to build a Tuple class that can be accessed like an Array. I could probably turn things into (void *) but that would defeat the purpose of the templates since I'm trying to get type-safety.
I'm compiling using VS2010 pro. My current non-working solution produces the following error.
Error: 'Item &MyList::operator ' : could not deduce template argument for 'N'.
<pre class="lang-cpp prettyprint-override">#include <tuple>
#include <stdio.h>
template <int size, typename Ty0,
typename Ty1=std::tr1::_Nil, typename Ty2=std::tr1::_Nil, typename Ty3=std::tr1::_Nil,
typename Ty4=std::tr1::_Nil, typename Ty5=std::tr1::_Nil, typename Ty6=std::tr1::_Nil,
typename Ty7=std::tr1::_Nil, typename Ty8=std::tr1::_Nil, typename Ty9=std::tr1::_Nil>
struct MyList {
std::tuple<Ty0, Ty1, Ty2, Ty3, Ty4, Ty5, Ty6, Ty7, Ty8, Ty9> items;
template <int N, typename Ty>
Ty &operator[](int N) {
auto &var = std::get<N>(items);
return var;
}
};
void main() {
MyList<2, int, double> list;
auto var = list[0];
}
<b>Potential Solutions: (edit)</b>
<ol><li><a href="http://cpptruths.blogspot.com/2012/01/array-like-access-and-iterators-for.html" rel="nofollow">Variadic templates with homogeneous data</a></li> <li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3413.html" rel="nofollow">Using constexpr C++11</a></li> </ol>Answer1:It depends what you want to index the tuple <em>with</em>. If you're using a runtime integer then clearly you can't attain type safety; there's no way for the compiler to know what type to return (other in the case where the tuple is homogeneous, for which see above).
If on the other hand you're just after the syntax of subscripting, you can do this using indexing objects with appropriate types, e.g. (for exposition) the ready-made std::placeholders
:
template<typename T>
typename std::tuple_element<std::is_placeholder<T>::value,
std::tuple<Ty0, Ty1, Ty2, Ty3, Ty4, Ty5, Ty6, Ty7, Ty8, Ty9>>::type &
operator[](T) { return std::get<std::is_placeholder<T>::value>(items); }
Usage:
using namespace std::placeholders;
auto var = list[_1];