我(最后)最近听说过可变参数模板。我想知道如果有一种方法可以使用编译时运算符来生成int - 多项式:
template <int... coefs>
struct polynom {}
哪个coud支持添加,一元减号和多元运算符。
[编辑]:输入问题:
int-polynomon基本上是一个整数列表(系数):
1 + 2x^2 - 7x^5 <=> (1, 0, 2, 0, 0, -7)
我希望这个多项式由编译时常量表示:
polynom<1,0,2,0,0,-7>
让我们首先考虑添加(我们逐个添加元素)。
是否有可能以某种方式运营商+:
polynom<1,0,1> + polynom<-1,2,1,3> -> polynom<0, 2, 2, 3>
对于乘法,它将是一个类似的(但更复杂的问题)。
有人在这有经验吗?
答案 0 :(得分:2)
这是我在10分钟内提出的,可能不是最优雅或最有效的解决方案,但非常简单,只使用无聊的沼泽标准递归方法而不是可变参数列表。
#include <iostream>
// our polynomials are little-endian: the first coefficient is for power 0,
// the second one is for power 1 etc
// The empty list corresponds to the zero polynomial
template <int ... coeff> struct Poly {};
// Print it out
template <int ... coeff> std::ostream& operator<< (std::ostream& os, Poly<coeff...>);
template <> std::ostream& operator<< (std::ostream& os, Poly<>) { return os; }
template <int coeff0, int ... coeff> std::ostream& operator<< (std::ostream& os, Poly<coeff0, coeff...>) {
os << coeff0 << " " << Poly<coeff...>();
}
// For number coeff0 and polynomial poly(x), return coeff0 + x * poly(x)
template <int coeff0, class poly> struct poly_shift;
template <int coeff0, int ... coeff> struct poly_shift<coeff0, Poly<coeff...>>{
using type = Poly<coeff0, coeff...>;
};
// Addition of polynomials
template <class poly1, class poly2>
struct poly_add;
template <>
struct poly_add<Poly<>, Poly<>> { using type = Poly<>; };
template <int ... coeff>
struct poly_add<Poly<coeff...>, Poly<>> { using type = Poly<coeff...>; };
template <int ... coeff>
struct poly_add<Poly<>, Poly<coeff...>> { using type = Poly<coeff...>; };
template <int coeff_l0, int coeff_r0, int... coeff_l, int... coeff_r>
struct poly_add<Poly<coeff_l0, coeff_l...>, Poly<coeff_r0, coeff_r...>> {
using type = typename poly_shift<coeff_l0 + coeff_r0, typename poly_add<Poly<coeff_l...>, Poly<coeff_r...>>::type>::type;
};
// convenient infix operator for values
template <class poly1, class poly2>
constexpr typename poly_add<poly1, poly2>::type operator+ (poly1 p1, poly2 p2) { return {}; }
// test it
int main()
{
Poly <1,2,3> a;
Poly <3,4,5,6> b;
std::cout << (a+b);
}
答案 1 :(得分:0)
我不明白你到底想要什么(你能提出一个使用的例子吗?)但是我认为一种方法是根据this.props.match
定义一组类型。
例如,一元减号可以定义如下
hdfs dfsadmin -setQuota <N> <directory>...<directory>
hdfs dfsadmin -clrQuota <directory>...<directory>
hdfs dfsadmin -setSpaceQuota <N> <directory>...<directory>
hdfs dfsadmin -clrSpaceQuota <directory>...<directory>
和add运算符如下
std::integral_constant
要简化表达式,可以按如下方式定义单个整数
template <typename T>
struct uminus
: std::integral_constant<typename T::value_type, - T::value>
{ };
所以你可以编写表达式(计算编译时间)如下
template <typename T1, typename T2>
struct add
: std::integral_constant<typename T1::value_type, T1::value + T2::value>
{ };
以下是一个完整的工作示例
template <int I>
struct i : std::integral_constant<int, I>
{ };