#思路
利用static_cast强制类型转换来读取各个元素。
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
template<class,class>
constexpr bool is_same_class = false;
template<class T>
constexpr bool is_same_class<T, T> = true;
template<int idx, typename ...args>
struct Element {};
template<typename ...Type>
class Mytuple;
template<int idx>
struct Element<idx, Mytuple<>> {
static_assert(idx < 0, "index out of range\n");
};
template<int idx, typename a, typename ...args>
struct Element<idx, Mytuple<a, args...>> :public Element<idx - 1, Mytuple<args...>> {};
template<class a, typename ...args>
struct Element<0, Mytuple<a, args...>> {
using value_type = a;
using tuple_type = Mytuple<a, args...>;
};
template<>
class Mytuple<> {
public:
constexpr Mytuple() noexcept = default;
};
template<typename This,typename ...Rest>
class Mytuple<This, Rest...> :public Mytuple<Rest...> {
public:
using This_type = This;
using MyBase = Mytuple<Rest...>;
This_type Myval;
constexpr Mytuple(This_type Arg, Rest ...args):Myval(Arg), MyBase(args...) {
}
template<size_t idx,class ...types>
friend constexpr typename Element<idx, Mytuple<types...>>::value_type& Mget(Mytuple<types...>& t);
};
template<size_t idx, class ...types>
constexpr typename Element<idx, Mytuple<types...>>::value_type& Mget(Mytuple<types...>& t)
{
using HType = typename Element<idx, Mytuple<types...>>::tuple_type;
return static_cast<HType&>(t).Myval;
};
int main() {
make_index_sequence<2> aa;
tuple<int,int,int> a(_Unpack_tuple_t{}, tuple<int,int,int>(3,3,4));
cout<<get<2>(a);
Mytuple<int,int,int> b(1, 2, 3);
cout << Mget<2>(b) << endl;
}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int test(int a, int b, int c) {
return a + b + c;
}
template<typename ...Types>
struct Mytuple;
template<>
struct Mytuple<> {
constexpr Mytuple() noexcept = default;
};
template<typename This, typename ...Rest>
struct Mytuple<This, Rest...> :public Mytuple<Rest...> {
public:
using Mytype = This;
using MyBase = Mytuple<Rest...>;
Mytype Myval;
Mytuple(Mytype arg, Rest ...args) :Myval(arg), MyBase(args...) {}
};
template<int idx, typename Mytuple>
struct Element:public Element<idx-1,typename Mytuple::MyBase> {
};
template<int idx>
struct Element<idx,Mytuple<>> {
static_assert(idx < 0, "index out of range");
};
template<typename Mytuple>
struct Element<0, Mytuple> {
using value_type = typename Mytuple::Mytype;
using tuple_type = Mytuple;
};
template<int idx,typename Mytuple>
typename Element<idx, Mytuple>::value_type get(Mytuple &val) {
using T = typename Element<idx, Mytuple>::tuple_type;
return static_cast<T>(val).Myval;
}
int main() {
Mytuple<int, int, int> t(1, 2, 3);
cout << get<2>(t) << endl;
}