Search code examples
c++templatesoverloadingeigenspecialization

How to overload/specialize template class function to handle arithmetic types and a container-class


I am trying to create a template class with a memberfunction which can handle arithmetic datatypes (int, char, float ...) and a container-class like Eigen::DenseBase<> or std::vector<>

Code to demonstrate my idea:

template <typename T>class myClass{
  ...
  void foo(T);
  ...
};

template <typename T> void myClass<T>::foo(T){
  //Function for arithmetic Datatypes
}
//Specialization does not work - What is the correct (best?) approach?
template <> void myClass<T>::foo(<Eigen::DenseBase<T>){
  //Function for Eigen::DenseBase<T> - Objects
}

This are my first steps with template-programming so I am looking forward to tipps and ideas how to solve this problem


Solution

  • What you are trying to do is called partial specialization. You are trying to specialize your foo to work differently for a family of types - i.e. types which are instantions of Eigen::DenseBase. Unfortunately, this is not possible.

    Member functions of template classes could only be fully-specialized, i.e. implementation could be provided for a specific type. For example, that would work:

        template <>
        void myClass<char*>::foo(char* );
    

    The only way to partially specialize your foo is to put it into partial specialization for the whole class. Something like that:

    template <typename T>
    class myClass{
      ...
      void foo(T);
      ...
    };
    
    template<class T> 
    class myClass<Eigen::DenseBase<T>> {
        void foo(Eigen::DenseBase<T> ) { ...}
    };
    

    The caveat here is that if you are (partially) specializing the class, you need to provide all the members which need to be there from the original template (often a lot of copy duplication). Standard solution here is to put everything which doesn't depend on partial specialization to the base class, and inherit your template and specialization from it.