从默认参数推导参数包

Deduce parameter pack from default argument

本文关键字:参数 默认      更新时间:2023-10-16

编译器是否可以从函数的默认参数中推断出参数包?特别是,我有以下代码:


template <int ... Is> struct seq {};
template <int ... Is> struct make_seq;
template <int head, int ... tail>
struct make_seq<head, tail...>
{
using type = typename make_seq<head - 1, head - 1, tail...>::type;
};
template <int ... Is>
struct make_seq<0, Is...>
{
using type = seq<Is...>;
};
template <int N>
using make_seq_t = typename make_seq<N>::type;
template<int N, int ...Is>
int deduceParamPack(seq<Is...> s = make_seq_t<N>{})
{
return sizeof...(Is);
}
int main()
{
return deduceParamPack<5>();
}

编译器将参数包推断为空,并尝试向其强制转换默认参数。相反,我想实现与以下类似的行为:

int main()
{
return deduceParamPack<5>(make_seq_t<5>{});
}

其中推导的参数包是0,1,2,3,4,而不显式传入此参数。

编译器是否可以从函数的默认参数中推断出参数包?

不,据我所知。

但。。。不完全是你问的...但也许您可以找到以下基于结构部分专业化的解决方案

template <std::size_t N, typename = std::make_index_sequence<N*N>>
struct deduceParamPackStruct;
template <std::size_t N, std::size_t ... Is>
struct deduceParamPackStruct<N, std::index_sequence<Is...>>
{
static constexpr std::size_t func ()
{ return sizeof...(Is); }
};

您可以按如下方式使用它

static_assert( 25 == deduceParamPackStruct<5>::func() );