递归要求的 C++ 模板类

标签 c++ templates

我正在尝试使用元编程代码对 Horner 算法进行编码。不幸的是,代码无法编译。在这里您可以找到编译器错误:

In instantiation of ‘const int tuple_nth_element_v<1u, int, 1>::value’:
----> LINE 1 <---- recursively required from ‘const int tuple_nth_element_v<2u, int, 2, 1>::value’
required from ‘const int tuple_nth_element_v<3u, int, 1, 2, 1>::value’
----> LINE 2 <---- recursively required from ‘constexpr const double Horner_Impl<5, 2ul, int, 1, 2, 1>::value’
required from ‘constexpr const double Horner_Impl<5, 3ul, int, 1, 2, 1>::value’
required from ‘constexpr const double Horner<5, int, 1, 2, 1>::value’
required from here
incomplete type ‘tuple_nth_element_v<0u, int>’ used in nested name specifier

代码使用了以下内容:

template<unsigned int N, class T, T... t>
struct tuple_nth_element_v;

template <class T, T t0, T... t>
struct tuple_nth_element_v<0, T, t0, t...> {
    static const T value = t0;
};
template <unsigned int N, class T, T t0, T... t>
struct tuple_nth_element_v<N, T, t0, t...> {
---> LINE1 <----
    static const T value = tuple_nth_element_v<N-1, T, t...>::value;
};


template<int x, std::size_t i, class T, T... a>
struct Horner_Impl
{
----> LINE 2 <----
    constexpr static double value = Horner_Impl<x, i - 1, T, a...>::value * x + 
    tuple_nth_element_v<sizeof...(a) - i, T , a...>::value;
};

template<int x, class T, T... a>
struct Horner_Impl<x, 0, T, a...>
{
    constexpr static double value = tuple_nth_element_v<sizeof...(a), T , a...>::value;
};

template<int x, class T, T... a>
struct Horner
{
    constexpr static double value = Horner_Impl<x, sizeof...(a), T, a...>::value;
};

有人会有想法吗?

最佳答案

这种方式对我来说似乎更直接一点,因为它在每次递归时都减少了一个系数,而不是使用辅助类来执行索引枚举:

#include <iostream>

template <int x, typename T, T a_n, T ...a>
struct Horner {
    constexpr static double value = Horner<x, T, a...>::value * x + a_n;
};

template <int x, typename T, T a_n>
struct Horner<x, T, a_n> {
    constexpr static double value = a_n;
};

int main() {
    double y = Horner<3, int, 5, 3, 2, 8>::value;
    std::cout << y << "\n";
}

关于递归要求的 C++ 模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076430/

相关文章:

php - 如何添加 jReject - jQuery 浏览器拒绝到 Joomla 1.5 网站

c++ - 如何使用 header 对象在 malloc 内存中安全地构造 C++ 对象

c++ - 如何在C++中生成内存映射

c++ - 通过 C 中的链表实现的堆栈

c++ - 聚合初始化 - vector 和数组

c++ - 是否可以使用模板元编程来编译时选择该类将执行的功能?

c++ - 了解使用 GCC 时编译时间花在哪里

c++ - 对象作为参数的析构函数被调用但不是构造函数?

C++ 模板 : Create a specialized function for a specific data type

templates - RSpec 功能测试中的 stub 模板