c++ - Extension of STL container through composition or free functions? -


say need new type in application, consists of std::vector<int> extended single function. straightforward way composition (due limitations in inheritance of stl containers):

class {     public:         a(std::vector<int> & vec) : vec_(vec) {}         int hash();     private:         std::vector<int> vec_ } 

this requires user first construct vector<int> , copy in constructor, bad when going handle sizeable number of large vectors. 1 could, of course, write pass-through push_back(), introduces mutable state, avoid.

so seems me, can either avoid copies or keep immutable, correct?

if so, simplest (and efficiency-wise equivalent) way use typedef , free functions @ namespace scope:

namespace n { typedef std::vector<int> a; int a_hash(const & a); } 

this feels wrong somehow, since extensions in future "pollute" namespace. also, calling a_hash(...) on vector<int> possible, might lead unexpected results (assuming impose constraints on user has follow or otherwise enforced in first example)

my 2 questions are:

  • how can 1 not sacrifice both immutability , efficiency when using above class code?
  • when make sense use free functions opposed encapsulation in classes/structs?

thank you!

hashing algorithm not type, , shouldn't restricted data in particular container type either. if want provide hashing, makes sense create functor computes hash 1 element (int, you've written things above) @ time, use std::accumulate or std::for_each apply collection:

namespace whatever {  struct hasher {      int current_hash; public:     hasher() : current_hash(0x1234) {}      // incredibly simplistic hash: xor values together.     operator()(int new_val) { current_hash ^= new_val; }     operator int() { return current_hash; } }; }  int hash = std::for_each(coll.begin(), coll.end(), whatever::hasher()); 

note allows coll vector, or deque or can use pair of istream_iterators hash data in file...


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -