Search code examples
c++c++11castingeigenstatic-cast

static_cast complex<short> to complex<double> in c++


I would like to use static_cast to convert complex< short > to complex< double >.

Convert complex<int16_t> to complex<double>

I am trying to do the same thing as in this post, but I need to use static_cast. The reason I cannot use that solution is because I am using Eigen which uses static_cast in its cast() function. Is there a way to extend the functionality of static_cast to convert in this way? Or is there a way to extend Eigen's cast() function to handle this conversion?

This is basically what I am attempting:

Eigen::Array<std::complex<short>, Eigen::Dynamic, 1> short_array;
Eigen::Array<std::complex<double>, Eigen::Dynamic, 1> double_array;
double_array = short_array.cast< std::complex<double> >();

Solution

  • The simplest is to specialize Eigen::internal::cast:

    template<>
    inline std::complex<double> cast(const std::complex<short>& x) {
      return std::complex<double>(std::real(x),std::imag(x));
    }
    

    Demo here.