如果您愿意明确描述结构成员,您可能会接近您想要的内容。
#include <iostream>
#include <tuple>
#include <functional>
using namespace std;
struct test
{
int i = 121;
double j = 234.0;
string k = "Some k";
};
struct anotherStruct
{
double t = 121.8;
};
struct undescribedStruct
{
string t = "Some undescribed";
};
tuple<int&, double&, string&> struct_as_tuple(test& t)
{
return tie( t.i, t.j, t.k);
}
tuple<double&> struct_as_tuple(anotherStruct& t)
{
return tie( t.t );
}
template<unsigned...> struct index_tuple{};
template<unsigned I, typename IndexTuple, typename... Types>
struct make_indices_impl;
template<unsigned I, unsigned... Indices, typename T, typename... Types>
struct make_indices_impl<I, index_tuple<Indices...>, T, Types...>
{
typedef typename
make_indices_impl<I + 1,
index_tuple<Indices..., I>,
Types...>::type type;
};
template<unsigned I, unsigned... Indices>
struct make_indices_impl<I, index_tuple<Indices...> >
{
typedef index_tuple<Indices...> type;
};
template<typename... Types>
struct make_indices
: make_indices_impl<0, index_tuple<>, Types...>
{};
void bar()
{
std::cout << endl;
}
template <typename T, typename... Args>
void bar(T&& t, Args&&... args)
{
std::cout << "T: [" << t << "] ";
return bar(forward<Args>(args)...);
}
template <unsigned... Indices, class... Args>
void foo_forward_call_impl(index_tuple<Indices...>,
std::tuple<Args...> tuple )
{
return bar(std::get<Indices>(tuple)...);
}
template<class... Args>
void foo_forward_call(std::tuple<Args...> tuple )
{
typedef typename make_indices<Args...>::type Indices;
return foo_forward_call_impl(Indices(), tuple);
}
template <typename T>
void foo(T&& t)
{
return foo_forward_call( struct_as_tuple(t) );
}
int main()
{
test t1;
foo(t1);
anotherStruct t2;
foo(t2);
undescribedStruct t3;
return 0;
}
你基本上需要为每种支持的类型提供一个从结构成员到元组的构造方式(请参阅struct_as_tuple)。
然后,foo根据传入的类型生成元组,并将其传递给元组展开实现。
这可能不是你想要的,但在此时此刻,这是我能想到的最接近它的方法...
to_array_ptr
成员函数)。 - SwiftMango