I am trying to write a simple class that will act as a complex<double>
number when used in a context that warrants a complex number, otherwise it will act as a double
(with the requirement that the imaginary part must be 0 when used this way)
This is what I have so far:
class Sample
{
public:
Sample() {}
Sample(double real) : m_data(real) {}
Sample(double real, double imaginary) : m_data(real, imaginary) {}
operator std::complex<double>() const
{
return m_data;
}
operator double() const
{
assert(m_data.imag() == 0.0);
return m_data.real();
}
private:
std::complex<double> m_data;
};
This works great for most situations. Anytime this class is passed to a function that expects a complex number it will act as though it is a complex number. Anytime it is passed to a function that expects a double it will act as though it is a double.
The problem arises when I pass it to a function that will accept BOTH complex numbers and doubles. (for example std::arg
). When I try to pass a Sample
object to std::arg
it doesn't know which conversion to use since both are technically valid.
In situations like this I want the complex
conversion to be "preferred" and have it just pass it as a complex. Is there any way to make one user defined function preferred over another when both conversions would be technically acceptable?