===================== template<class T> class any { public: T m_data; }; void main() { any<int> a; }
缺点是 必须知道类型,有时我们并不知道某个对象的类型。
------------- class any { public: template<class T> any(const T& t) { m_pData = new T(t); } protected: void* m_pData; }; void main() { any a(3); }
void*是不安全的。
-------------- #include <iostream> using namespace std ; class any { public: template<class T> any(const T& t) { m_pData = new CType<T>(t); } //析构函数省略 class CTypeRoot {}; template<class T> class CType : public CTypeRoot { public: CType(const T& t):m_value(t) { } T m_value; }; public: CTypeRoot* m_pData; }; void main() { any a(3); }
可以编译通过了,但无法取值。
=============== #include <iostream> #include <string> using namespace std ; class any { public: template<class T> any(const T& t) { m_pData = new CType<T>(t); } //析构函数省略 class CTypeRoot {}; template<class T> class CType : public CTypeRoot { public: CType(const T& t):m_value(t) { } T m_value; }; public: CTypeRoot* m_pData; }; template<typename ValueType> ValueType any_cast(const any& operand,const ValueType tDefault = ValueType() ) { any::CType<ValueType>* p = static_cast<any::CType<ValueType>* >(operand.m_pData); return p->m_value; } void main() { any a(3); int y = any_cast<int>(a); // string y1 = any_cast<string>(a); //运行出错 }