具有条件的模板专用化

Template specialization with condition

本文关键字:专用 有条件      更新时间:2023-10-16

我们正在为使用递归模板的范围编写一个通用实现

template<typename T, std::size_t n>
class range<T,n> {
  // actual implementation
};
// Specialication for n = 0

实际实现可以在 https://github.com/jyujin/libefgy/blob/master/include/ef.gy/range.h

到目前为止,这很好用,但如果范围超过 256 个元素,您会遇到问题,因为您有一个有限制的模板递归。

为了防止这种情况,我们的想法是专门化超过一定数量的所有内容,例如大小 n 超过 255。

你怎么能写一些条件,可能使用enable_if?

一种可能的解决方案/解决方法是将给定的模板实例化为

template class range<int, 255>;

所以现在,您将有一个新的n限制,这将是255 + recursiveLimit .
您还必须专门化类型 T :-/

编辑现在我们有了 OP 的代码:)

据我了解,您的递归是创建一个序列 {0, 1, 2, .., N - 1}
执行此操作的线性方法将在N == limit立即达到递归限制。

以下将使用分而治之来完成这项工作:
所以你应该在N ~= 2 ** limit时达到极限

template <int ... Is> struct index_sequence {};
// Helper to concatenate several sequences
template<typename ... Ts> struct concat_seq;
template<int ... Is, int ...Is2, typename ... Ts>
struct concat_seq<index_sequence<Is...>, index_sequence<Is2...>, Ts...>
{
    typedef typename concat_seq<index_sequence<Is..., Is2...>, Ts...>::type type;
};
template<int ... Is>
struct concat_seq<index_sequence<Is...>>
{
    typedef index_sequence<Is...> type;
};
// Some test
static_assert(std::is_same<typename concat_seq<index_sequence<1>, index_sequence<2>, index_sequence<3>>::type, index_sequence<1, 2, 3>>::value, "");

// Helper to create the sequence
template <int N, int Offset = 0> struct make_seq;
template <int Offset> struct make_seq<0, Offset>
{
    typedef index_sequence<> type;
};
template <int Offset> struct make_seq<1, Offset>
{
    typedef index_sequence<Offset> type;
};
// Split the sequence to generate in two part (recursively)
template <int N, int Offset> struct make_seq
{
    typedef typename concat_seq<typename make_seq<N / 2, Offset>::type,
                                typename make_seq<N - N / 2, Offset + N / 2>::type>::type type;
};
// test
static_assert(std::is_same<typename make_seq<5>::type, index_sequence<0, 1, 2, 3, 4>>::value, "");
static_assert(std::is_same<typename make_seq<5, 2>::type, index_sequence<2, 3, 4, 5, 6>>::value, "");
// Final test
template struct make_seq<10000>; // This work for me