Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templated operator[]... possible? Useful?

Tags:

c++

templates

Could you have:

template <class T>
const T &operator[] (unsigned int x)

My thinking was if you have a map<string,string> it would be nice to have a wrapper class which lets you do:

obj["IntVal"]="12";
obj["StringVal"]="Test";

int i = obj["IntVal"];

How close to this can we actually get in C++? Is it worth the pain?

like image 587
Mr. Boy Avatar asked Mar 22 '26 04:03

Mr. Boy


1 Answers

You can also do

class Class {
  struct Proxy {
    template<typename T> T as() { ... }
    template<typename T> operator T() { return as<T>(); }
  private:
    Proxy(...) { ... }
    Proxy(Proxy const&); // noncopyable
    Proxy &operator=(Proxy const&);
    friend class Class;
  };

public:
  Proxy operator[](std::string const& s) { ... }
};

Class a;
int i = a["foo"];
int i = a["foo"].as<int>();

T will be deduced to whatever the to be initialized object is. And you are not allowed to copy the proxy. That said, i prefer an explicit as<T> function like another one proposed too.

like image 162
Johannes Schaub - litb Avatar answered Mar 24 '26 17:03

Johannes Schaub - litb



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!