C++中如何判断数字是否为复数?
有没有这样的内置函数?:
isComplex(1)->false
C++ 是一种强类型语言,文字
1
始终是 int
。
您询问的确定可能与转换文本时相关...
isComplex("1")
,为此您可以尝试流式传输:
std::istringstream iss(some_text);
std::complex<double> my_complex;
char c;
if (iss >> my_complex && // conversion possible...
!(iss >> c)) // no unconverted non-whitespace characters afterwards
...use my_complex...
else
throw std::runtime_error("input was not a valid complex number");
另外,如果您在模板内并且不确定类型参数是否为
std::complex
,您可以使用例如进行测试std::is_same<T, std::is_complex<double>>::value
,例如:
#include <iostream>
#include <complex>
#include <type_traits>
using namespace std;
double get_real(double n) { return n; }
double get_real(const std::complex<double>& n) { return n.real(); }
template <typename T>
std::complex<double> f(T n)
{
if (std::is_same<T, std::complex<double>>::value)
return n * std::complex<double>{1, -1} + get_real(n);
else
return -n;
}
int main()
{
std::cout << f(std::complex<double>{10, 10}) << '\n';
std::cout << f(10.0) << '\n';
}
输出:
(30,0)
(-10,0)
查看代码这里。
对于更复杂的函数,您可能需要创建单独的重载,例如
double
和std::complex<double>
,和/或float
和std::complex<float>
,long double
等..
可以使用模板专门化来进行此类检查:
template<typename T>
bool IsComplexSimpler(const T&){
return false;
}
template<typename T>
bool IsComplexSimpler(const std::complex<T>&){
return true;
}
int main() {
std::cout << IsComplexSimpler(5) << std::endl;
std::cout << IsComplexSimpler(std::complex<double>(4,3)) << std::endl;
}
我已经看到使用 SFINAE 和 std::enable_if 的其他答案,但这更简单。