gpt4 book ai didi

递归要求的 C++ 模板类

转载 作者:行者123 更新时间:2023-11-30 03:43:28 25 4
gpt4 key购买 nike

我正在尝试使用元编程代码对 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/

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