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

C++ 是否可以用模板函数替换两个类似的成员函数?,c++,class,templates,C++,Class,Templates,比如说 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()。谢谢。即使类

比如说

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 */;
}
模板
myType func(myType a){
/*做点什么;
}

是的,这是可能的,请参见SO问题。

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

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

尝试时发生了什么?(提示:是的,您可以创建模板成员函数。)