Is opIndexAssign possible in C ++?

D Version 2 programming language has a great way to overload an expression like this :

classInstance[someName] = someValue; 

Or as a function of D defined in this small example :

 ref Map opIndexAssign(ref const(ValueT) value, ref const(NameT) name) { this.insert(name, value); return this; } 

Is this possible in C ++ (ideally without using STL)? If so, how?

+4
source share
2 answers

Normally you should use the proxy object as the return type operator[] ; this object will have a custom operator= . The vector<bool> specialization in the C ++ Standard Library uses a proxy server to get the behavior you are looking for. However, the proxy-based solution is not as transparent as version D. The code looks something like this:

 class proxy; class my_map { public: proxy operator[](const key_type& k); // Rest of class }; class proxy { my_map& m; key_type k; friend class my_map; proxy(my_map& m, const key_type& k): m(m), k(k) {} public: operator value_type() const {return m.read(k);} proxy& operator=(const value_type& v) {m.write(k, v); return *this;} }; proxy my_map::operator[](const key_type& k) { return proxy(*this, k); } 
+8
source

Not familiar with D, will I have to assume that your first code fragment ends with an opIndexAssign call using value = someValue and name = someName ?

If so, it can be done in C ++, but not so simple. You can overload the [] operator and return the proxy object using the special = operator as follows (a very simple, far-fetched example):

 class MyProxy { public: MyProxy (int& ref) : valueRef(ref) { } MyProxy& operator = (int value) { valueRef = value; return *this; } private: int& valueRef; }; class MyClass { public: MyProxy operator [] (std::string name); private: int myVal; }; MyProxy& MyClass::operator [] (std::string name) { if (name.compare("myVal")) return MyProxy(myVal); ... } int main ( ) { MyClass mc; mc["myVal"] = 10; // Sets mc.myVal to 10 } 

I would like to emphasize that the above is not a very beautiful / well-formed code, just an illustration. It has not been tested.

EDIT: Too fast for me Jeremiah !!!

+3
source

Source: https://habr.com/ru/post/1339084/


All Articles