I was looking at the C++ library <complex>
, and noticed that functions such as std::conj
and std::norm
are free functions i.e. static functions not placed inside the std::complex
class. Why is this the case?
I would've thought that, from a C++ OOP design perspective, it would've made more sense to have e.g. complex<T> complex<T>::conj()
and complex<T> complex<T>::norm()
as methods so that I can call auto norm = z.norm()
instead of auto norm = std::norm(z)
.
Am I missing something about how the standard library is designed which justifies why these functions are free?
Best Answer
The C++ standard library does not exclusively follow the OO design paradigm.
Free functions, when combined with parameter overloading, play much nicer when you are writing templated code that should work with both class types and primitive types.
For example, suppose I have a list of values (either complex, as
std::complex<float>
, or real, asfloat
) and I want to compare them on magnitude. Then I can write a comparison function likeWriting such a function would not be possible if
abs
forstd::complex<T>
would have been a member function based on OO design principles.