我有一個DeviceSettingsManager
類,看起來像:的std ::不同參數的個數成員函數映射
class DeviceSettingsManager
{
int32_t PropertyA();
void SetPropertyA(int32_t prop);
std::string PropertyB();
void SetPropertyB(std::string prop);
// about 50 properties go here ...
}
,我需要根據屬性字符串我必須設置屬性。沒有代碼看起來像這樣:
// Parse property string ("PropertyA = 100, PropertyB = xyz, ...") to key/value pairs
if (key == "PropertyA")
manager.SetPropertyA(value);
else if (key == "PropertyB")
manager.SetPropertyB(value);
// 50 more properties ...
不是很好吧?
第一個想法是存儲在制定者的地圖:
setters_[key](value); // where for example key == "PropertyA" and value = 100
但有一個問題:我無法在地圖不同的仿函數存儲:
typedef boost::function<void(int32_t)> setter_int_t;
typedef boost::function<void(std::string)> setter_string_t;
std::map<std::string, ???> setters_;
當然,我可以有兩張地圖(int32_t
和std::string
)。但它不能很好地擴展。如果我將被迫添加新參數類型如float
或double
甚至user_defined_class
,我將需要更多地圖。
其他方法是用boost::any
通過在這種情況下我需要reinterpret_cast
回到boost::function
我需要的,所以再次面對問題。
問題:我如何管理這樣的PropertyManagers,以防止編寫數十億個if-else語句?