How do you access the imaginary unit without "using namespace std::complex_literals"?

Viewed 152

I am currently working with complex numbers. I need something to represent the imaginary unit. One way to do that would be to define a variable

std::complex<double> imaginary_unit{0, 1};

However, I have found that there is a built in imaginary unit i. This unit is discussed, for example, in the question here.

The suggested solution is the following:

#include <complex>
using namespace std::complex_literals;

and then to use the constant i like below:

std::complex<double> z1 = 1i * 1i;

I have been taught that using namespace is bad style and can create problems for people that use my headers. I have tried to access this built in constant i in a verbose way, but so far I haven't succeeded. Two failed examples are below:

// error: namespace std::literals::complex_literals has no member i
std::literals::complex_literals::i
// error: more than one instance of overloaded function
std::literals::complex_literals::operator""i(3.0) 

How do I access the constant i without defining my own i or using namespace?

1 Answers

You could create your unit constant like this:

constexpr auto imaginary_unit = std::literals::complex_literals::operator""i(1.L);

... but if you don't use the literal namespace, std::complex<double> imaginary_unit{0, 1}; is preferable. It's shorter and easier to read.

... the constant i ...

i is not a constant. It's a user-defined literal. One possible implementation:

constexpr std::complex<double> operator""i(long double d) {
    return std::complex<double>{0.0, static_cast<double>(d)};
}

I don't think you should be afraid of using the literal namespaces. They are there to simplify life.

Related