如何重载/专业化模板类函数以处理算术类型和容器类 [英] How to overload/specialize template class function to handle arithmetic types and a container-class
问题描述
我正在尝试创建一个具有成员函数的模板类,该成员函数可以处理算术数据类型(int,char,float ...)和一个容器类,例如Eigen :: DenseBase<>或std :: vector<>
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<>
代码来证明我的想法:
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
推荐答案
您要尝试的工作称为部分专业化。您正在尝试 specialize 您的 foo
以针对一系列类型(即,类型为 Eigen的实例)进行不同的工作: :DenseBase
。不幸的是,这是不可能的。
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* );
对foo进行部分专业化的唯一方法是将其对整个类进行部分专业化。诸如此类:
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.
这篇关于如何重载/专业化模板类函数以处理算术类型和容器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!