c – 如何在提供`T = std :: complex`时避免嵌入`std :: complex`?

前端之家收集整理的这篇文章主要介绍了c – 如何在提供`T = std :: complex`时避免嵌入`std :: complex`?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于多项式方程求解器,将其模板化以使任何类型可用是很好的:
  1. template <class number,int degree>
  2. class PolynomialEquation
  3. {
  4. public:
  5.  
  6. private:
  7. array<number,degree+1> myEquation;
  8. array<complex<number>,degree> equationResult;
  9. };

例如,这允许doubleinℝ用于输入,结果是std :: complex< double>在ℂ(我们知道从2级及以上,方程的解通常落入ℂ,例如:x ^ 2 1).

但是,等式的输入也可以是std :: complex.在这种情况下,myEquation的类型应该是复杂的,但equationResult不应该是std :: complex< complex< T>>,而只是类型T的正常复数.

问题:

当方程式与std :: complex一起提供时,如何使equationResult的类型成为std :: complex的子类型?

是否有std :: is_floating_point等同于std :: is_complex_number?

解决方法

您可以创建一个特征,例如:
  1. template <typename T>
  2. struct to_complex {
  3. using type = std::complex<T>;
  4. };
  5.  
  6. template <typename T>
  7. struct to_complex<std::complex<T>> {
  8. using type = std::complex<T>;
  9. };

然后

  1. template <class number,degree+1> myEquation;
  2. array<typename to_complex<number>::type,degree> equationResult;
  3. };

猜你在找的C&C++相关文章