2014-04-06 41 views
0

對不起,如果標題有點混亂,但我有一個問題,關於我的實體屬性系統。你可以傳遞數據到一個空指針而不用指向變量的指針

當一個屬性被註冊,它的投入到這個unordered_map:

std::unordered_map<std::string, void*> m_attributes; 

下面是註冊使用它的屬性

void registerAttribute(const std::string& id, void* data) 
{ 
    m_attributes[id] = data; 
} 

和示例實現:

std::shared_ptr<int> health(new int(20)); 

registerAttribute("health", health.get()); 

我想要做的是這樣的:

registerAttribute("health", 20); 

我不想指向數據,因爲它很煩人,只是臃腫的代碼。有什麼方法可以實現我想要的嗎?

謝謝!

+0

std :: shared_ptr的使用是毫無意義的,在這裏 –

回答

2

採取步驟輸入省音,你可能想利用的boost ::任何:

#include <iostream> 
#include <map> 
#include <boost/any.hpp> 

typedef std::map<std::string, boost::any> any_map; 

int main(int argc, char *argv[]) { 
    any_map map; 
    map.insert(any_map::value_type("health", 20)); 
    std::cout << boost::any_cast<int>(map.begin()->second) << '\n'; 
    return 0; 
} 
0

爲了得到某物地址的指針利用它作爲一個void*,必須有一個對象哪些工作。 void*的值只是保存數據的內存的地址。表達式20不滿足此要求,因爲它的存儲將在表達式後消失。

取決於必要在你的地圖,你可以簡化值類型的聲明價值普遍性。如果他們真的總是int然後使用它。否則,你可以考慮使用類似boost::variantboost::any的東西來在你的地圖中創建更多的常規值類型。

相關問題