在“get part of std::tuple”的帮助下:
#include <iostream>
#include <string>
#include <algorithm>
#include <tuple>
//SEE https://stackoverflow.com/questions/8569567/get-part-of-stdtuple
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
template <size_t... n>
struct ct_integers_list {
template <size_t m>
struct push_back
{
typedef ct_integers_list<n..., m> type;
};
};
template <size_t max>
struct ct_iota_1
{
typedef typename ct_iota_1<max - 1>::type::template push_back<max>::type type;
};
template <>
struct ct_iota_1<0>
{
typedef ct_integers_list<> type;
};
template <size_t... indices, typename Tuple>
auto tuple_subset(const Tuple& tpl, ct_integers_list<indices...>)
-> decltype(std::make_tuple(std::get<indices>(tpl)...))
{
return std::make_tuple(std::get<indices>(tpl)...);
// this means:
// make_tuple(get<indices[0]>(tpl), get<indices[1]>(tpl), ...)
}
template <typename Head, typename... Tail>
std::tuple<Tail...> tuple_tail(const std::tuple<Head, Tail...>& tpl)
{
return tuple_subset(tpl, typename ct_iota_1<sizeof...(Tail)>::type());
// this means:
// tuple_subset<1, 2, 3, ..., sizeof...(Tail)-1>(tpl, ..)
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//SEE https://stackoverflow.com/questions/8569567/get-part-of-stdtuple
struct A
{
A call(const int&) {
std::cout << "int" << std::endl;
return *this;
}
A call(const std::string& s) {
std::cout << "string" << std::endl;
return *this;
}
template <typename T>
A call(std::tuple<T> tpl)
{
return call(std::get<0>(tpl));
}
template <typename T, typename...Types>
A call(std::tuple<T, Types...> tpl)
{
return call(std::get<0>(tpl)).call(tuple_tail(tpl));
}
} a;
int main()
{
std::tuple<int, std::string, int, int, std::string> t(0, "1", 2, 3, "4");
A b = a.call(t);
}
输出:
int
string
int
int
string