是否可以仅针对类的特定模板实例声明成员函数?这就是为什么我要这样做:

// Polynomial<N> is a polynomial of degree N
template<int N>
class Polynomial {
public:
    //... various shared methods e.g...
    double eval(double x) const;
    Polynomial<N-1> derivative() const;
    Polynomial<N+1> integralFrom(double x0) const;
    // ... various shared operators etc.

    double zero() const; // only want Polynomial<1> to support this
    // only want Polynomial<2> and Polynomial<1> to support the following
    //     because the solutions rapidly become too difficult to implement
    std::vector<double> zeros() const;
    std::vector<double> stationaryPoints() const { return derivative().zeros();}

private:
    std::array<double,2> coeffs;
}

我当前的解决方法是仅将Polynomial<N>::zeros()N>2引发异常,但在编译时检测该问题将非常好。

最佳答案

您可以使用CRTP在知道派生类的基类中实现zeroszero

然后有条件地从具有zeros和/或zero的代码派生。

template<class P>
struct zeros { /* todo */ };

template<class P>
struct zero:zeros<P> { /* todo */ };

struct nozero {};

template<int N>
struxt Polynomial:
  std::conditional_t<
    (N==1),
    zero<Polynomial<N>>,
    std::conditional_t<
      (N==2),
      zeros<Polynomial<N>>,
      nozero
    >
  >
{
  // body
};

10-08 10:48