开发者

Call function when items are added or removed from a vector

I'm writing a widget kit for the Nano-X window system. In my base class view, I have a vector defined:

std::vector<RSMKit::View *> children;

Is it possible to call a function (GrReparentWindow in this case) when an item is开发者_开发百科 added or removed from the vector so that the newly added widget can be shown?


No, this is not possible. You also should not subclass std::vector to overwrite push_back and erase, because the class has not been designed for it. However, it would be simple to write your own container that would use std::vector for storage and expose Add and Remove functions with callbacks. Something along the following lines:

template<typename T>
class CallbackVector
{
public:

    typedef void (*Callback)();

private:

    std::vector<T> elements;
    Callback       OnAdd;
    Callback       OnRemove;

public:

    CallbackVector(Callback OnAdd, Callback OnRemove)
        : OnAdd    (OnAdd)
        , OnRemove (OnRemove)
    {
    }

    void Add(const T & element)
    {
        elements.push_back(element);
        OnAdd();
    }

    void Remove(int i)
    {
        elements.erase(elements.begin() + i);
        OnRemove();
    }
};

In practice, you would probably want a more complicated callback, using a function with a pointer parameter or using boost::function.


No. Do not inherit from std::vector. Just encapsulate it.

template<typename T> struct MyVector
{
private:
    std::vector<T> items;
public:
    void push_back (const T& x)
    {
        // Do something here
        items.push_back(x);
    }
    // etc
};


One possible solution is to subclass your vector class and add callbacks on the insertion and removal methods. With an stl vector this is not possible by default


There are two ways;

(1) Inherit std::vector and overload push_back() and pop_back() method:

template<typename T>
struct MyVector : std::vector<T>
{
  void push_back (const T& x)
  {
    GrReparentWindow ();
    vector<T>::push_back(x);
  }
  // same way pop_back()
};

Usage:

MyVector<RSMKit::View*> children;
children.push_back(new RSMKint::View);

(2) Another way is to push_back the items with custom overloaded operator or method; if you are allowed to edit RSMKit::View

class RSMKit::View
{
//...
public:
  RSMKit::View* get ()
  {
    GrReparentWindow ();
    return this;
  }
};

Usage:

MyVector<RSMKit::View*> children;
RSMKit::View *p = new RSMKint::View;
children.push_back(p->get());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜