How can I identify if the number is complex in C++?
Is there any built in function like this?:
isComplex(1)->false
C++ is a strongly typed language, and the literal 1
is always an int
.
The determination you ask about might be relevant when converting text... isComplex("1")
, for that you can attempt streaming:
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");
Separately, if you're inside a template and not sure whether a type parameter is std::complex
, you can test with e.g. std::is_same<T, std::is_complex<double>>::value
, for example:
#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';
}
Output:
(30,0)
(-10,0)
See the code here.
For more complicated functions, you may want to create separate overloads for e.g. double
and std::complex<double>
, and/or float
and std::complex<float>
, long double
etc..