gpt4 book ai didi

c++ - 模板尾部结构 raise "incomplete type in nested name specifier"

转载 作者:搜寻专家 更新时间:2023-10-31 00:28:00 26 4
gpt4 key购买 nike

我试图操纵 C++14 integer_sequence,但我遇到了一个错误 I不明白。让我们从提高可读性的捷径开始

template <typename Int, Int...ints>
using IS = std::integer_sequence<Int, ints...>;

我正在使用 sum 函数减少 IS。我没有为空定义它故意排序,因为在我使用的实际用例中就是这种情况gcd、lcm等算术函数:

template<typename ...Int> struct redsum;

template<typename Int, Int i0, Int i1, Int... ints>
struct redsum< IS<Int, i0, i1, ints...> > :
redsum< IS<Int, i0 + i1, ints...> > { };

template<typename Int, Int i0>
struct redsum<IS<Int, i0> > : std::integral_constant< Int, i0 > { };

现在我想定义尾部(lisp 中的 cdr):

template<typename Int, Int ...ints> struct tail;

template<typename Int, Int i0, Int... ints>
struct tail<Int, i0, ints...> : IS<Int, ints...> { };

template<typename Int, Int... ints>
struct tail<IS<Int, ints...> > : tail<Int, ints...> { };

但这并没有像预期的那样工作:

// This works as expected
static_assert(redsum< IS<unsigned, 2, 5, 12, 18> >::value == 2 + 5 + 12 + 18);

// This doesn't with an incomplete type error
static_assert(redsum< tail < IS<unsigned, 2, 5, 12, 18> > >::value == 5 + 12 + 18);// EDIT

我不明白我的类型在这个用例中哪里不完整。任何解释或建议我应该如何写得更好?

最佳答案

您所有的 redsum 模板特化都期望模板参数是 std::integer_sequence 类型。尽管 tail 类最终继承自 std::integer_sequence,但它本身不会匹配特化所期望的类型,因此编译器回退到(未定义的)主要类型模板。这种情况下的经典方法是在终止递归的类模板特化中定义嵌套类型:

template <typename Int, Int ...ints>
struct tail;

template <typename Int, Int i0, Int... ints>
struct tail<Int, i0, ints...> { using type = IS<Int, ints...>; };
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

template <typename Int, Int... ints>
struct tail<IS<Int, ints...>> : tail<Int, ints...> {};

然后访问嵌套类型以获取此转换的结果:

 redsum< tail < IS<unsigned, 2, 5, 12, 18> >::type >::value
// ~~~~~^

关于c++ - 模板尾部结构 raise "incomplete type in nested name specifier",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46998986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com