Simple way to add implicit type promotion to the std::complex class operators

匆匆过客 提交于 2019-12-24 19:29:16

问题


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?


回答1:


Here is probably what you want:

#include <complex>
#include <utility> // declval

template <typename T, typename U>
auto operator +(const ::std::complex<T> &a, ::std::complex<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});
}

auto test()
{
    using ::std::complex;
    complex<double> x{0, 0};
    complex<long double> y{0, 0};
    return x+y;
}

This requires C++14 for the 'auto' (aka deduced) return type. For C++11 you'd basically have to repeat the decltype expression inside the operator for the return type.



来源:https://stackoverflow.com/questions/47562514/simple-way-to-add-implicit-type-promotion-to-the-stdcomplex-class-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!