|
class CAny
{
class HolderBase
{
public:
virtual ~HolderBase(){}
};
template<typename T>
class Holder : public HolderBase
{
friend CAny;
T t_;
public:
Holder(const T& t)
:t_(t)
{
}
};
HolderBase *hb_;
// map<string, CAny> member_;
public:
CAny()
{
hb_ = 0;
}
~CAny()
{
delete hb_;
}
CAny(const CAny& xld);
template<typename T>
CAny(const T& d);
CAny& operator=(const CAny& xld);
template<typename T>
CAny& operator=(const T& d);
CAny operator[](const string& key);
};
CAny::CAny(const CAny& xld)
{
hb_ = new Holder<CAny>(xld);
}
template<typename T>
CAny::CAny(const T& d)
{
hb_ = new Holder<T>(d);
}
CAny& CAny::operator=(const CAny& xld)
{
delete hb_;
hb_ = new Holder<CAny>(xld);
return *this;
}
template<typename T>
CAny& CAny::operator=(const T& d)
{
delete hb_;
hb_ = new Holder<T>(d);
return *this;
}
CAny CAny::operator[](const string& key)
{
//return (*(*dynamic_cast<Holder<map<string, shared_ptr<CAny> > > *>(hb_)))[key];
typedef map<string, CAny> MapHolder;
Holder<MapHolder> *ptr = (Holder<MapHolder> *)hb_;
return (*ptr)[key];
}
我实现了一个类似于any的东西,但是编译不过
我想让他能够有如下功能
CAny x;
x["name"] = string("brightsun")
CAny y;
y["country"] = string("china")
y["province"] = string("beijing")
x["address"] = y;
x["age"] = 100;
cout << x << endl;
请达人解答,谢谢! |
|