Take the 2-minute tour ×

I was brushing up on my C++ and wanted to implement a concept based on Scott Meyer's 'More Effective C++', Item 30. The thing is about distinguishing between reading and writing when using a subscript operator with a custom data structure.

So what I'm experimenting with is to create a template used as follows:

map<int> im;
im["foo"] = 69;
cout << im["foo"] << endl; // outputs 69
im["bar"] = im["foo"];

I came up with something like this, having a STL map inside the class for storing data and creating a Helper proxy class to handle dealing with subscript stuff.

#include <iostream>
#include <map>
using std::string;

namespace mymap {

template <typename T> class map
   std::map<string,T> container;


   class Helper {
      map& m;
      string key;
      Helper (map& mm, string kkey): m(mm), key(kkey) {};


      operator T() const // rvalue use
         std::cout << "op char()" << std::endl;
         return m.container[key];

      Helper& operator=(T i) // lvalue use
         m.container[key] = i;
         return *this;

      Helper& operator=(const Helper& rhs) // lvalue use
         m.container[key] = rhs.m.container[rhs.key];
         return *this;

   const Helper operator[]( string key) const // for const maps
      return Helper(const_cast<map&>(*this), key);

   Helper operator[](string key) // for non-const maps
      return Helper(*this, key);

   friend class Helper;


} // mymap namespace

Although it builds for an instruction

 using namespace mymap;
 using mymap::map;
 using std::cout;

 int main(void) 
     map<int> im;

in main(), but any other of the stuff I'm trying to accomplish breaks the build. Could you please tell me if there's something significant that I screwed up and how that can be fixed?

It might be the templates structure, as I see in the first place:

error: ‘mymap::map<T>::Helper::Helper(mymap::map<T>&, std::string) [with T = int, mymap::map<T> = mymap::map<int>, std::string = std::basic_string<char>]’ is private

I've seen a simmilar design concept with proxies at Two array subscript overloading to read and write, however I'm willing to try the Meyer's approach in this one.

share|improve this question
Did you read the error? It says you can't create objects of type Helper because the constructor Helper::Helper is private. Which is true. Helper should probably friend class map. –  Ben Voigt Sep 20 '13 at 4:41
well, that was it - thanks for pointing it out. Now I see it was a 'brilliant' question to start with here. –  adverin Sep 20 '13 at 12:39
add comment


Your Answer



Browse other questions tagged or ask your own question.