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.
1
int
The determination you ask about might be relevant when converting text... isComplex("1"), for that you can attempt streaming:
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");
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:
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'; }
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..
double
std::complex<double>
float
std::complex<float>
long double
Copyright © 2021 Jogjafile Inc.
C++ is a strongly typed language, and the literal
1
is always anint
.The determination you ask about might be relevant when converting text...
isComplex("1")
, for that you can attempt streaming: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:Output:
See the code here.
For more complicated functions, you may want to create separate overloads for e.g.
double
andstd::complex<double>
, and/orfloat
andstd::complex<float>
,long double
etc..