【问题标题】:Is that possible to replace two similar member functions with a template function?是否可以用模板函数替换两个相似的成员函数?
【发布时间】:2012-01-11 03:35:06
【问题描述】:

例如

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()。谢谢。

【问题讨论】:

  • 你尝试的时候发生了什么? (提示:是的,您可以制作模板成员函数。)

标签: c++ class templates


【解决方案1】:

即使类本身没有模板化,您也可以编写模板化的成员函数,就像编写不是类的方法的模板化函数一样。

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

【讨论】:

    【解决方案2】:

    是的,有可能,请参阅this SO 问题。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-28
        • 2017-02-28
        • 1970-01-01
        • 2020-12-08
        • 1970-01-01
        • 2022-12-13
        • 2011-01-22
        相关资源
        最近更新 更多