Search code examples
c++delegateswrapperforwarding

Delegate/forward function to member (composition)


Suppose I have the class

template<class T>
class Vector
{
  public:
    Vector() = default;

    inline size_t size() const { return _vector.size(); }

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

Is there any way to delegate functions (or operators) to _vector, at compile time, without overhead ?

I can of course (and it's what I'm doing) forward everything by declaring every functions I need, and just call the appropriate function to the member, as I did with size().

This article propose exactly what I would need. For example using this :

template<class T>
class Vector
{
  public:
    Vector() = default;

  private :
    std::vector<T> _vector;

  public:
    using _vector {
      size_t size() const;
      void push_back(const T&);
    }
};

The compiler would then generate the appropriate code. But I didn't find anything like this, is it possible ?


Solution

  • First way: You can inherit std::vector<T> publicly to make such delegation possible:

    template<class T>
    class Vector : public std::vector<T>
    ...
    

    Whether to inherit std::vector or not is little debatable, but then it's your code.

    Second way: If you are particular about the composition then make Vector<T> objects behave as smart pointers:

    template<typename T>
    class Vector
    {
      std::vector<T> _vector;    
    public:
      std::vector<T>* operator -> () { return &_vector; }
    };
    Vector<int> vi;
    vi->size(); // instead of vi.size()
    

    Third way: Overload operator () for syntactic sugar:

    template<typename T>
    class Vector
    {
      std::vector<T> _vector;
    public:
      std::vector<T>& operator ()() { return _vector; }
      const std::vector<T>& operator ()() const { return _vector; }
    };
    Vector<int> vi;
    vi().size(); // instead of vi.size()