一个神奇的???whatever~~
一个神奇的类,用来封装消息数据,统一数据传递接口,从unity引擎源码拷贝而来。
#include <iostream> #include <assert.h> #include <crtdefs.h> struct MessageData { int type; private: // Note: on Metro WinRT types cannot be located in union, so don't use union! intptr_t data; public: MessageData () { data = 0; type = 0; } template<class T> void SetData (T inData, int classId) { // Check if SetData is used instead of SetScriptingObjectData //assert (type !=-1); //assert (sizeof (T) > sizeof (data)); // increase the data size *reinterpret_cast<T*> (&data) = *reinterpret_cast<T*> (&inData); type = classId; } template<class T> T GetData () { // Check if GetData is used instead of GetScriptingObjectData assert (type != -1); return *reinterpret_cast<T*> (&data); } intptr_t& GetGenericDataRef () { // Check if GetGenericDataRef is used instead of GetScriptingObjectData assert (type != -1); return data; } }; class test { public: test(int x) { m_date = x; } void print() { std::cout<<m_date<<std::endl; } private: int m_date ; }; int main() { MessageData data; test t(4); data.SetData(&t, 2); test * tt = data.GetData<test*>(); tt->print(); return 0; }