Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping STL in order to extend

So I read that inheritance from STL is a bad idea. But what about wrapping STL classes inside other classes in order to extend them. This with the main purpose of separating levels of abstraction, among other things.

Something like:

template<class T>
class MyVector{
public:
T& last(){
  return data[data.size() - 1]
}

bool include(T& element);

//etc.

private:
vector<T> data;
}

Is this a good idea? Is this something c++ programmers do often?

Thank you.

like image 474
nahpr Avatar asked Nov 23 '25 10:11

nahpr


1 Answers

Yes, wrapping is better than inheritance, but only if you need to add state to an existing data structure. Otherwise, add non-member functions. This is explained in more detail in item 35 of C++ Coding Standards (Amazon)

To add state, prefer composition instead of inheritance. Admittedly, it's tedious to have to write passthrough functions for the member functions you want to keep, but such an implementation is vastly better and safer than using public or nonpublic inheritance.

template<typename T>
class MyExtendedVector
{
public:
    // pass-through functions for std::vector members
    void some_existing_fun() { return vec_.some_existing_fun(); }

    // new functionality that uses extra state
    void some_new_fun() { // your implementation here }   

private: 
    std::vector<T> vec_;
    // extra state e.g. to do logging, caching, or whatever
};

To add behavior, prefer to add nonmem-ber functions instead of member functions.

However make sure to make your algorithms as generic as possible:

// if you CAN: write algorithm that uses iterators only 
// (and delegates to iterator category that container supports)
template<typename Iterator, typename T>
bool generic_contains(Iterator first, Iterator last, T const& elem)
{
    // implement using iterators + STL algorithms only
    return std::find(first, last, elem) != last;
}

// if you MUST: write algorithm that uses specific interface of container
template<typename T>
void vector_contains(std::vector<T> const& v, T const& elem)
{
    // implement using public interface of Container + STL algorithms
    return generic_contains(v.begin(), v.end(), elem);
}
like image 160
TemplateRex Avatar answered Nov 26 '25 00:11

TemplateRex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!