Re: [問題] 非靜態,access by type 的 data member

作者: chubiei (:))   2014-07-01 00:44:21
版大的寫法太隱晦了
其實這邊需要的是動態的type註冊系統
http://ideone.com/oPvexQ
這邊的 TypeRegistry 其實相當於版大用的 maximum size:
版大的作法是每加入一個新的type
底下的memory array會利用 maximum size以及sizeof(value)自動調整
因此這邊可以顯而易見一個問題就是
當多個Foo instance存在 而且每個instance需要存放不同的type object的話
底下的memory array會產生浪費
而且使用char array會遭遇到麻煩的constructor/destructor問題
需要再寫其他code去包裝
相反 利用TypeRegistry的作法
將 type <-> id 的 index 和存放 value 的 Foo 本身做脫勾
每一個 type 都會拿到自己獨特的 id
Foo 本身只要處理好依照 id 存取的 code 即可
因此這邊可以看情況看隨意代換底下的 value store:
如果將 value store 換成是 vector 就會 fallback 成版大的 code
浪費一點空間 但是存取是 O(1)
這邊是用 map 完全不會浪費空間 但是存取是 O(lg N)
※ 引述《yoco315 (眠月)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: Standard C++11 or beyond
: 問題(Question):
: 想要請各位大大,是否存在一種手法,
: 能讓我以 type 來 access data member?
: 會想要用 type 來存取,是因為我根據不同的 type 需要存取到不同的值,
: 但因為是 template,到底會有哪些 type 其實我不確定。
: 舉個例子來說
: struct Foo {
: template <typename T>
: T& get() {
: static T v;
: return v;
: }
: }
: 這樣我就可以透過下面這種手法來「模擬」用 type 來存取 data member
: Foo a;
: a.get<int>() = 5;
: a.get<int>()++;
: std::cout << a.get<int>() << std::endl; // 印出 6
: a.get<float>() = 3.14;
: std::cout << a.get<float>() << std::endl; // 印出 3.14
: 這個方法的缺點,是這些模擬出來的 data member 一定都是 static 的
: 因為當我
: Foo a;
: Foo b;
: a.get<int>() = 5;
: std::cout << b.get<int>() << std::endl; // 印出 5
: 那我現在很想知道有沒有一種手法可以讓我同時滿足下面三個條件:
: 1. 可以透過 type 來自動的生成 data member
: 當然,會有哪些 type,在 compile time 就已經確定
: 但使用可以不用明確指定會有 int, float, Bar, 等等
: 要像上面那種例子一樣,compiler 要能自己蒐集所有的使用點
: 2. 要是 non-static 的!
: a.get<X>() 跟 b.get<X>() 要是不同人
: 3. 要有效率,希望能避開下面這種作法
: struct Foo {
: template <typename T>
: T& get() {
: static std::map<Foo*, T> m;
: return m[this]; // 既然是 static,那我透過 this 來 map 可以吧
: }
: };
: 百思不得其解,盼前輩解惑。
: 小妹先謝過了。
作者: LPH66 (-6.2598534e+18f)   2014-07-01 01:14:00
ID 的話或許可以學一下 LLVM 的做法, 它用一個 class static的成員變數的指標當 ID, 初始化時會向子類別要一個這種指標因為該變數是各類別獨有, 其位址就是一個方便的索引

Links booklink

Contact Us: admin [ a t ] ucptt.com