Writing out the implementation of std::tuple_element

Can someone tell me why the following does not compile? (only the last line in main() does not compile actually). How to fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <tuple>

template <std::size_t N, typename...TYPES>
struct TupleElement;

template <typename FIRST, typename...REST>
struct TupleElement<0, std::tuple<FIRST, REST...>> {
    typedef FIRST type;
};

template <int N, typename FIRST, typename...REST>
struct TupleElement<N, std::tuple<FIRST, REST...>> {
    typedef typename TupleElement<N-1, std::tuple<REST...>>::type type;
};

int main() {
	std::tuple<int, char, double> myTuple = std::make_tuple(2, 'a', 3.14);
	TupleElement<2, decltype(myTuple)>::type d;
}
What compiler are you using and what does it say, exactly? Clang compiles with no diagnostics: http://coliru.stacked-crooked.com/a/c63bc1250ce21496

GCC 4.8.1:
tuple.cpp: In function 'int main()':
tuple.cpp:20:2: error: incomplete type 'TupleElement<2u, std::tuple<int, char, double> >' used in nested name specifier
TupleElement<2, decltype(myTuple)>::type d;
^
tuple.cpp:20:43: error: expected ';' before 'd'
TupleElement<2, decltype(myTuple)>::type d;
^
I think there is still some flaw still in the code, even if clang does accept it. The correct implementation I think needs to be longer than this.
Last edited on
I see: your primary template is for std::size_t, but your specialization is for int. Make them the same type.
Ah! The std::size_t was there because I was writing the implementation for std::tuple_size before and I lazily used copy and paste. Thanks.
Topic archived. No new replies allowed.