你能拥有:
template <class T>
const T &operator[] (unsigned int x)
Run Code Online (Sandbox Code Playgroud)
我的想法是,如果你有map<string,string>一个包装类可以让你做的很好:
obj["IntVal"]="12";
obj["StringVal"]="Test";
int i = obj["IntVal"];
Run Code Online (Sandbox Code Playgroud)
我们实际上可以用C++接近这个?值得痛苦吗?
你也可以
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>();
Run Code Online (Sandbox Code Playgroud)
T将推断出要初始化的对象是什么.并且您不能复制代理.也就是说,我更喜欢as<T>像另一个提议的显式功能.