我们正在编写一个使用递归模板的范围的通用实现
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
关于c++ - 有条件的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808556/