是否可以用模板函数替换两个相似的成员函数?

Is that possible to replace two similar member functions with a template function?

本文关键字:函数 两个 相似 成员 替换 是否      更新时间:2023-10-16

例如

class A {
 public:
   void fun(Array a);
   void fun(Vector a);
   /* Most codes in these two functions are same. */
   /* Can certainly be merged into a template function if they were not member functions. */
}

请注意,我希望在a班有这两个版本的fun()。谢谢。

即使类本身没有被模板化,也可以像编写非类方法的模板化函数那样编写被模板化的成员函数。

template <class myType >
myType func (myType a) {
 /* do something */;
}

是可能的,看这个SO问题

可以像创建普通函数一样创建模板成员函数。只要保持代码的泛型,就像它可以在涉及向量和其他数据类型的情况下工作一样。

template <typename T>
void fun(T var) {}