Search code examples
c++11templatestemplate-specializationeigen3

Template specialization for template


I have a function which uses the Eigen C++ library:

 template <class Type1>
 void myFunction ( const Eigen::MatrixBase<Type1>& matrix)
 {

 }

Now, I would like to specialize the template function "myFunction" for the type std::complex<Type>. Note that the type "std::complex<Type>" is again a template. How to define such a function?


Solution

  • You have to note that Eigen::MatrixBase<std::complex<...> > is not a valid type, since MatrixBase is a CRTP-base class. E.g., Matrix<double,2,2> inherits (indirectly) from MatrixBase<Matrix<double,2,2> >, etc. However, every MatrixBase provides a Scalar type which you can check using SFINAE (i.e., using std::enable_if):

    template <class Derived>
    typename std::enable_if<Eigen::NumTraits<typename Derived::Scalar>::IsComplex, void>::type 
    myFunction(const Eigen::MatrixBase<Derived>& matrix) {
        std::cout << "Passed complex\n";
    }
    
    template <class Derived>
    typename std::enable_if<!Eigen::NumTraits<typename Derived::Scalar>::IsComplex, void>::type 
    myFunction(const Eigen::MatrixBase<Derived>& matrix) {
        std::cout << "Passed non-complex\n";
    }
    

    Godbolt-Demo: https://godbolt.org/z/Q9YlPz