对于多项式方程求解器,将其模板化为任何类型都是很好的:
template <class number, int degree>
class PolynomialEquation
{
public:
private:
array<number, degree+1> myEquation;
array<complex<number>, degree> equationResult;
};
这允许,例如,ℝ中的double
用于输入,结果为{std::complex<double>
(我们知道从2级及以上,方程的解决方案通常会下降进入ℂ,例如:x ^ 2 + 1)。
但是,等式的输入也可以是std::complex
。在这种情况下,myEquation
的类型应该很复杂,但equationResult
不应该是std::complex<complex<T>>
,而只是T
类型的正常复数。
问题:
如果equationResult
提供等式时,如何将std::complex
的类型设为std::complex
的子类型?
是否有std::is_floating_point
等效的std :: is_complex_number?
答案 0 :(得分:7)
您可以创建一个特征,例如:
template <typename T>
struct to_complex {
using type = std::complex<T>;
};
template <typename T>
struct to_complex<std::complex<T>> {
using type = std::complex<T>;
};
然后
template <class number, int degree>
class PolynomialEquation
{
public:
private:
array<number, degree+1> myEquation;
array<typename to_complex<number>::type, degree> equationResult;
};
答案 1 :(得分:2)
我认为检查类型是否是一个复杂的数字并不存在特征,但创建一个类型应该相对容易(也是Jarod的to_complex
的替代实现):
#include <type_traits>
#include <complex>
#include <iostream>
template <class T>
struct is_complex_number: std::false_type { };
template <class T>
struct is_complex_number<std::complex<T>>: std::true_type { };
template <class T>
struct to_complex: std::conditional<is_complex_number<T>::value, T, std::complex<T>> { };
int main() {
std::cout << is_complex_number<float>::value << std::endl; // output: 0
std::cout << is_complex_number<std::complex<float>>::value << std::endl; // output: 1
typename to_complex<float>::type c; // decltype(c) == complex<float>
typename to_complex<std::complex<float>>::type d; // decltype(d) == complex<float>
}
答案 2 :(得分:2)
这里是@ W.F。
的C ++ 14单行代替using Complex = typename std::conditional<std::is_arithmetic<T>::value, std::complex<T>, T>::type;
假设如果它不是算术类型,那么它应该是一个复杂的。如果你想彻底,你需要确保T是算术(甚至浮点)或复杂。您需要将其与@ W.F混合使用。 anwser。
答案 3 :(得分:2)
我有一个多项式类,我可能想要实数系数和复数x(以及实数,实数和复数,复数)。我做了一个is_complex:
/**
* Introspection class to detect if a type is std::complex.
*/
template<typename _Tp>
struct is_complex : public std::false_type
{ };
/**
* Introspection class to detect if a type is std::complex.
*/
template<>
template<typename _Tp>
struct is_complex<std::complex<_Tp>> : public std::true_type
{ };
/**
* Introspection type to detect if a type is std::complex.
*/
template<typename _Tp>
using is_complex_t = typename is_complex<_Tp>::type;
/**
* Introspection variable template to detect if a type is std::complex.
*/
template<typename _Tp>
constexpr bool is_complex_v = is_complex<_Tp>::value;
另外,我使用工具来提取标量类型,无论输入是标量还是复杂,所以我可以使用数字限制工具,例如:
template<typename Tp>
struct num_traits
{
using __value_type = Tp;
};
template<>
template<typename Tp>
struct num_traits<std::complex<Tp>>
{
using __value_type = typename std::complex<Tp>::value_type;
};
template<typename Tp>
using num_traits_t = typename num_traits<Tp>::__value_type;
我可以这样使用:
using Val = num_traits_t<Ret>;
constexpr auto eps = std::numeric_limits<Val>::epsilon();
随后为实际和复杂输入构建收敛测试。