2015-07-11 34 views
0

有沒有一種標準的方式來改變容器內的類型,如std :: vector? 這方面的一個例子是具有:真正的動態矢量打字

std::vector<std::string> v; 

v.insert("hi"); 

然後改變類型某種程度上和添加:

v.insert(1); 

非常相似,如何解釋語言能夠有多種類型在列表/陣列

我知道載體本身並不這樣做,但是我失去了如何避免使用第三方庫如boost,甚至與我沒有方向。

我創建了一個示例代碼來展示一種鍵值數據方法。它確實有效,然而中間的(非工作)評論部分是我試圖實現的想法。

#include <iostream> 
#include <iterator> 
#include <vector> 
#include <map> 
#include <string> 
#include <typeinfo> 

using namespace std; 

int main() 
{ 
    typedef std::map<std::string, std::string> map_type; 
    typedef std::vector<map_type> vector_type; 
    typedef std::map<std::string, map_type> map_keyobj_type; 
    vector_type stack; 
    vector_type::iterator it = stack.begin(); 

    //First map 
    map_type stringmap; 
    stringmap.insert(map_type::value_type("I'm a string", "Also a String")); 
    it = stack.insert(it, stringmap); 

    //Second wanted map, example code of what is wanted 
    /* 
    map_keyobj_type secondlayer; 
    map_type secondlayervalue; 
    secondlayervalue.insert(map_type::value_type("String from inside map",  "That too string")); 
    secondlayer.insert(map_keyobj_type::value_type("List", secondlayervalue)); 
    stack.insert(it, secondlayer); 
    */ 

    map_type stringmap2; 
    stringmap2.insert(map_type::value_type("String after map map", "Also string")); 
    it = stack.insert(it, stringmap2); 


    //prints stack, only supports map_type 
    //Iterates backwards to get top-down input correct. 
    for (int i = stack.size()-1; i > -1; --i) 
    { 
     //Print map_type 
     if (typeid(stack[i]).name() == typeid(map_type).name()) 
     { 
      for (map_type::const_iterator ite = stack[i].begin(); ite != stack[i].end(); ++ite) 
      { 
       cout << ite->first << " : " << ite->second << "\n"; 
      } 
     } 
    } 

    //return 0; 
} 
+1

有[boost.any](http://www.boost.org/doc/libs/1_58_0/doc/html/any.html)。最好的方式去。 –

+0

隨着模板的工作方式,這不是微不足道的。查看JSON庫的做法。 –

+0

使用'boost :: any'或者阻止你自己的一個類似的函數。但是,請記住,如果您想要抵消它,除非您的任何類在編譯時具有了解該類型的魔術功能,否則您將必須進行類型轉換... – Joe

回答

0

我不確定這是最好的解決方案,但您可以嘗試使用QVariant達到此目的。如果你不能使用Qt,也許你應該爲此目的實施自己的班級。

+0

我實際上正在使用QT作爲GUI應用程序,它將使用上面提到的那種數據結構,但是我想單獨發佈它,並且可以將它集成到任何C++項目中。我將如何去實施一個這樣的課程?任何類似的例子? – CZauX

+0

如果你有'Qt'源代碼,那麼我建議你檢查'QVariant'的代碼,並嘗試製作你自己的副本,但我認爲這是一個更簡單的版本。 –

1

你可以使用boost :: any,訣竅是你需要知道你保存了什麼類型才能把它取出。如果你關心,這也是相當低效的,因爲它可以節省一些指針你的整數代替一個整數。

您可以使用歧視聯盟。這是一個包含枚舉和聯合的結構。枚舉告訴你的代碼在聯合中保存了什麼類型。

您提到了解釋型語言。他們大多數使用歧視聯盟方法。在Python或Perl的SV中查看PyObject。

+0

也許值得一提的是boost :: variant,所以OP不必從頭開始編寫歧視聯盟。 –