Question

I have written the following function to apply various math operations to each element of a vector:

namespace MYFUNCTION
{
    template<class T>
    std::vector<T> eop(const std::vector<T> &v1, T (*f)(T))
    {
        std::vector<T> v2(v1.size());
        for(int ii = 0; ii < v1.size(); ii++)
        {
            v2[ii] = (*f)(v1[ii]);
        }
        return v2;
    }
}

I have also overloaded the cosh() function for std::vector parameters:

namespace MYFUNCTION
{
    template<class T>
    std::vector<T> cosh(const std::vector<T> v1)
    {
        return eop(v1,static_cast<T (*)(T)>(&std::cosh));
    }
}

If I use this function for type double every thing is fine. If I use std::complex<double> instead I get a compiler error.

std::vector<double> a(2);
a[0] = 1.0;
a[1] = 2.0;
std::cout << MYFUNCTION::cosh(a) << std::endl; // Works fine.

std::vector<std::complex<double> > b(2);
b[0] = 1.0 + std::complex<double>(0.0,1.0);
b[1] = 2.0;
std::cout << MYFUNCTION::cosh(b) << std::endl; // Compiler error.

The compiler error is:

error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘std::complex<double> (*)(std::complex<double>)’

EDIT: This is the what the cosh function looks like in complex.h:

template<class T> complex<T> cosh (const complex<T>& x);

This is the what the cosh function looks like in cmath.h:

double cosh (double x);

I have included both complex.h and cmath.h.

Was it helpful?

Solution

Since std::cosh for std::complex<T> is a function template, &std::cosh doesn't make sense to the compiler because std::cosh is not a function, it is a template of family of functions. You need to write another overload to handle this case:

#include <complex> //it is where std::cosh<T> is defined

template<class T>
std::vector<std::complex<T>> cosh(std::vector<std::complex<T>> const & v1)
{
    typedef std::complex<T> cosh_type( std::complex<T> const &);
    return eop(v1, static_cast<cosh_type*>(&std::cosh<T>) );
}

By the way, pass the argument by reference to avoid unnecessary copies.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top