鉴于以下来自Anthony Williams的代码片段。一个非常基本的元组示例,这里的所有内容都按预期工作。
#include <iostream>
template<typename ... Types>
class simple_tuple;
template<>
class simple_tuple<>
{};
template<typename First,typename ... Rest>
class simple_tuple<First,Rest...>:
private simple_tuple<Rest...>
{
First member;
public:
simple_tuple(First const& f,Rest const& ... rest):
simple_tuple<Rest...>(rest...),
member(f)
{}
First const& head() const
{
return member;
}
simple_tuple<Rest...> const& rest() const
{
return *this;
}
};
template<unsigned index,typename ... Types>
struct simple_tuple_entry;
template<typename First,typename ... Types>
struct simple_tuple_entry<0,First,Types...>
{
typedef First const& type;
static type value(simple_tuple<First,Types...> const& tuple)
{
return tuple.head();
}
};
template<unsigned index,typename First,typename ... Types>
struct simple_tuple_entry<index,First,Types...>
{
typedef typename simple_tuple_entry<index-1,Types...>::type type;
static type value(simple_tuple<First,Types...> const& tuple)
{
return simple_tuple_entry<index-1,Types...>::value(tuple.rest());
}
};
template<unsigned index,typename ... Types>
typename simple_tuple_entry<index,Types...>::type
get_tuple_entry(simple_tuple<Types...> const& tuple)
{
std::cout << "SizeofArgs == " << sizeof...(Types) << std::endl;
return simple_tuple_entry<index,Types...>::value(tuple);
}
int main()
{
simple_tuple<int,char,double> st(42,'a',3.141);
std::cout<<get_tuple_entry<0>(st)<<","
<<get_tuple_entry<1>(st)<<","
<<get_tuple_entry<2>(st)<<std::endl;
}
但我想知道这个get_tuple_entry
功能。
我认为每次调用的可变参数模板参数的数量会有所不同,但 sizeof 总是返回 3。
所以该函数在某种程度上等同于以下(伪代码)
template<unsigned index, <int,char,double> >
typename simple_tuple_entry<index, <int,char,double> >::type
get_tuple_entry(simple_tuple<int,char,double> const& tuple)
{
std::cout << "SizeofArgs == " << sizeof...(<int,char,double>) << std::endl;
return simple_tuple_entry<index,<int,char,double> >::value(tuple);
}
但这意味着它get_tuple_entry
仅被返回值重载,这是不可能的。为什么每次通话的签名都不同?