2011-12-02 24 views
1

例如有可能用模板函数替换两个相似的成员函数吗?

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. */ 
} 

请注意,我希望能有两个类答:谢谢乐趣()这两个版本。

+0

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

+0

是吗?什么是问题。 –

回答

2

即使类本身不是模板化的,也可以编写一个成员函数,该函数的模板化方式与编写不是某个类的方法的模板化函数的方式相同。

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

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

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