c++functiontypesoperators

How to store std::complex operator as a variable (C++)


I've been writing some tests for the arithmetic of complex numbers.

I've tried to write them in a way where I don't have to rewrite a code section for each operator. I am trying to store std::complex overloaded operators such as operator+, operator+=, operator-, operator-= in a std::function variable. The reason why I need the std::complex operators is because I need to check them against my own implementation of complex numbers.

However, I can't get it to work, mostly because there seems to be a mismatch between the type of the variable (std::function) and the type of the value (std::complex operators). How should I write the code so that I can store these operator functions in a std::function variable?

This is my attempt, but alas it doesn't work:

std::function<void(std::complex<double>&, const std::complex<double>&)> var = 
                                               &std::complex<double>::operator+=;

Solution

  • You should check the documentation of std::complex::operator+=.

    Note the template version has only one overload:

    constexpr complex& operator+=( const T& other ); // (1)
    

    which does not match your case (you are expecting argument type const std::complex<T>&).

    Now, if you take a look lower in the doc, you will see another template version of operator+=:

    template<class X>
    constexpr complex& operator+=( const std::complex<X>& other ); // (5)
    

    So you need this to make it work:

    std::function<void(std::complex<double>&, const std::complex<double>&)> var = 
                                                   &std::complex<double>::operator+=<double>;
    

    Note the extra <double>!

    https://godbolt.org/z/TPGMe435s

    Note that this operator should also work when adding std::complex with different base types, that is why the template of member function is needed, so std::complex<float> and std::complex<double> could be added.