简体   繁体   English

如何重写STL容器功能

[英]how to override STL container function

It's possible, that override some function stl container with the same paremeters? 是否有可能用相同的参数重写某些功能stl容器? I want override exactly push_back with some if inside function. 我想用某些if内部函数完全覆盖push_back I try but, always have error/information about that function is in vector. 我尝试但是总是有关于该函数的错误/信息在矢量中。

Inheritance for STL containers is bad approach. STL容器的继承是不好的方法。 The vector is not supposed to have derived classes. 该向量不应该具有派生类。 There are no virtual method in the vector and virtual destructor ( the last one could make a lot of problems ). 向量和虚拟析构函数中没有虚拟方法(最后一个可能产生很多问题)。 You can create your own class and use vector as member. 您可以创建自己的类并使用vector作为成员。

Overriding means that you are going to inherit from STL container. 覆盖意味着您将从STL容器继承。 Don't do that! 不要那样做! STL containers are not designed for inheriting from them. STL容器不适用于从其继承。


As an option, you might encapsulate std::vector into some wrapper class and perform additional functionality before pushing, something like: 作为一种选择,您可以将std :: vector封装到一些包装器类中,并在推送之前执行其他功能,例如:

template<typename T>
class Wrapper
{
public:
    template<typename U>
    void push(U&& e)
    {
         // some additional processing
         data.push_back(std::forward<U>(e));
    }

private:
    std::vector<T> data;
};

You cant do that. 你不能那样做。 Most classes in the std library are not meant to be inherited from. std库中的大多数类都不是要继承的。 However, instead of changing it "from the inside" just do it "from the outside", for example: 但是,不要“从内部”进行更改,而只是“从外部”进行更改,例如:

template<typename T> myPush(std::vector<T>& v,T element) {
    if (someCondition()) { v.push(element); }
}

Alternatively, you could do this: 或者,您可以这样做:

struct MyCustomVector {
     void my_push( T element);
     /* pulic or private: */          // depends on what you want/need
     std::vector<T> vect;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM