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

一笑奈何 提交于 2019-12-11 17:42:27

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/53560473/how-to-overload-specialize-template-class-function-to-handle-arithmetic-types-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!