具有条件的模板专用化
Template specialization with condition
我们正在为使用递归模板的范围编写一个通用实现
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
相关文章:
- 如何使用 soong 命名空间来有条件地编译模块
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 根据模板类型有条件地删除变量
- 有条件地选择带有 decltype() 和三元运算符的类型
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 有条件的打印和计数在 std::map 上有限制
- 如何在 c++ 中有条件地包含标头?
- 如何仅在Qt是用ltcg构建时才有条件地启用ltcg?
- 如何在Visual Studio 2019中有条件地编译c++源文件
- C++可以有条件地向下转换类指针吗
- 使用 SFINAE 有条件地解析分配器成员
- 有条件地删除宏
- 有条件地包含C++标准库
- 如何有条件地将元素添加到 std::array - C++11
- 是否根据编译器版本有条件地包含源文件
- 有条件地启用类C++构造函数
- 我可以有条件地使用多个参数吗?
- 有条件地使用 Boost Python 添加模块
- 有什么东西阻止std::optional::value_or()有条件地不例外吗?
- 无法使用三元运算符有条件地分配"istream &"?