gpt4 book ai didi

c++ - 仅为类的特定模板实例化声明成员函数

转载 作者:行者123 更新时间:2023-11-30 05:25:18 24 4
gpt4 key购买 nike

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

// 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但如果能在编译时检测到问题就好了。

最佳答案

您还可以使用 std::enable_if 使 SFINAE 远离零函数。

template< int I >
class Poly {

public:
template<int Ib = I, typename = std::enable_if_t<Ib == 1> >
double zero()
{
return 42;
}
};

int main()
{
Poly< 10 > does_not_compile;
does_not_compile.zero();

//Poly< 1 > compile;
//compile.zero();
}

关于c++ - 仅为类的特定模板实例化声明成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344647/

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