I would like to allow the implicit conversion when summing two complex numbers
std::complex<double> a; std::complex<long double> b;
auto c = a+b;
I tried to implement what was suggested here C++ implicit type conversion with template
I defined a derived class of std::complex and I added the friend function that should allow the implicit conversion. Here is my code:
template <typename T> class Complex : private std::complex<T> {
friend Complex operator+ (Complex const &lhs, Complex const &rhs) return Complex(); };
int main(){
Complex<double> C1; Complex<long double> C2;
auto Sum = C1+C2;
return(0); }
I don't understand if the problem is in the inheritance from std::complex or in the friend function. Any help would be highly appreciated, Thanks
EDIT:
Omnifarious code works great when left and right arguments of operator+ are both std::complex. How could I allow also the operation complex + int?
Here is my attempt:
template <typename T, typename U>
auto operator +(const ::std::complex<T> &a, std::enable_if_t<std::is_arithmetic<U>::value, U> &b)
{
typedef decltype(::std::declval<T>() + ::std::declval<U>()) comcomp_t;
typedef ::std::complex<comcomp_t> result_t;
return ::std::operator +(result_t{a}, result_t{b});
}
But, when I try:
int i=1;
auto sum = C1+i;
it doesn't compile. "couldn't deduce template parameter ‘U’"
Why?