【发布时间】:2020-02-22 17:24:47
【问题描述】:
我正在尝试使用模板来表示简单的多项式,例如 x^2 + 3x + 5。我的想法是将它们表示为项的总和,每个项都有一个系数和一个幂,例如x^2 具有 coeff=1 和 power=2。我还希望能够评估某些 x 的多项式(它们只有 1 个未知数,但在很多地方)。到目前为止,我有:
struct PolyEnd{
double eval(double x){
return 0;
}
};
template <int coeff, int power, class Tail> struct Poly {
typedef Tail tt;
double eval(double x){
double curr = coeff * std::pow(x, power);
return curr; // has to call eval(x) on rest of the terms which are in the tail and return the sum with "curr"
}
};
int main()
{
double x = 2;
Poly<1,1,Poly<1,1,PolyEnd>> poly;
std::cout << poly.eval(x) << std::endl;
return 0;
}
但是,我被卡住了。我正在尝试的甚至可能吗?如果是这样,我怎样才能使递归 eval() 调用起作用?
【问题讨论】:
标签: c++ templates template-meta-programming template-specialization