我们可以用自定义函数扩展现有的类吗? (无继承)

Posted

技术标签:

【中文标题】我们可以用自定义函数扩展现有的类吗? (无继承)【英文标题】:Can we extend existing classes with custom functions? (No inheritance) 【发布时间】:2015-03-21 12:55:44 【问题描述】:

我正在寻找一种使用自定义成员方法扩展 C++ 类的方法。就像 C# 对 Linq 扩展所做的那样:

public static class Factory

    public static int getIndex(this List<int> source, int value)
    
        int index = 0;
        foreach (int item in source)
        
            if (item == value)
                return index;
            index++;
        
        return -1;
    

此 C# 代码将为列表的每个实例添加一个方法。所以你可以写:

List<int> myList = new List<int>();
myList.Add(26);
myList.Add(42);
myList.Add(37);
myList.Add(3);
int index = myList.getIndex(42);

这在 C++ 中也有可能吗?如何正确地将这样的方法添加到 std::vector&lt;T&gt; 无需子类化

抱歉,如果这是重复的,如果不使用继承,我找不到任何回答我的问题的东西。

【问题讨论】:

【参考方案1】:

如果您的意图仅仅是扩展标准 c++ 容器类,您应该考虑算法而不是成员方法。

考虑一下这段代码。 为了简洁,没有错误检查

#include <vector>
#include <set>
#include <iostream>

// returns the second element
template< typename T>
int getSecond(T begin)

  begin++;
  return *begin;



int main()


  std::vector<int> intlist;
  intlist.push_back(1);
  intlist.push_back(2);
  intlist.push_back(3);

  std::set<int> intset;
  intset.insert(1);
  intset.insert(3);
  intset.insert(2);

  std::cout << "Second in vector " << getSecond(intlist.begin()) << std::endl;
  std::cout << "Second in set " << getSecond(intset.begin()) << std::endl;


现在可以假设将 getSecond 建模为 std::vector 的成员,但将其建模为采用迭代器的独立函数非常强大,因为相同的函数可以用于集合双端队列等。

如果你有 N 个容器和 M 算法作为成员函数,你将有 N * M 个函数,但作为独立的算法函数,会有大大减少代码

【讨论】:

为什么是后增量?你不需要副作用。 @JorenHeit 这只是风格。在大多数实际情况下,它对性能没有影响。 是的,我知道这可以通过独立的功能和模板来实现。但是到目前为止我只在我的程序中使用std::vector,如果我可以用我的成员函数扩展这个类,它将大大提高可读性。 在这种情况下,为什么不做 class myvector : public std::vector 并在任何地方使用 myvector @parapurarajkumar 我听说它继承 std 类的不良行为

以上是关于我们可以用自定义函数扩展现有的类吗? (无继承)的主要内容,如果未能解决你的问题,请参考以下文章

自定义异常类

用自定义函数替换 Print 语句调用

OC中类别扩展协议与委托

python怎样用自定义函数对列表排序?

python可否用自定义函数对数据进行插值

继承的纯虚函数