boost::function vs function pointers
我正在实现通用设置阅读器。
我的想法是,我有一个应用程序,其设置可以是布尔值,整数和字符串。
然后我有一个Config类,在其中实现了用于此类设置的吸气剂,config类将构造函数中的客户作为对象,以便它知道它将为该客户读取设置。
我无法正常工作,我想我误用了boost :: function和普通函数指针。
在映射中,我想引用,而
问题是没有typedef的情况下我不能使用函数指针,这会使模板工作变得复杂,任何更明智的解决方案?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #include"Config.h" class ConfigReader { ConfigReader(); template<class R> R readConfig(std::string customer, std::string settingName); private: typedef bool (Config::* BoolConfigFunctor) () const; std::map<std::string, BoolConfigFunctor> boolConfigMap; typedef int(Config::* IntConfigFunctor) () const; std::map<std::string, IntConfigFunctor> integerConfigMap; typedef std::string (Config::* StrConfigFunctor) () const; std::map<std::string, StrConfigFunctor> stringConfigMap; template<class R> std::map<std::string, R (Config::* ) () > getConfigMap(); } ConfigReader() { // INIT all settings you want to be readable in the functor maps boolConfigMap["USE_NEW_VERSION"] = &Config::useNewVersion; boolConfigMap["MAINTENANCE_MODE"] = &Config::isMaintenance; integerConfigMap["TIMEOUT"] = &Config::getTimeout; stringConfigMap["USERNAME"] = &Config::getUserName; ... } template<class R> R readConfig(std::string customer, std::string settingName) { R returnValue; typedef typename std::map<AMD_STD::string, R (Config::* ) () > ConfigMap_t; typedef typename ConfigMap_t::const_iterator ConfigMapIter_t; ConfigMap_t configMap = getConfigMap<R>(); ConfigMapIter_t configIter = configMap.find(settingName); if (configIter != configMap.end()) { Config config(customer); // Real instance of Config against which we want to call the function boost::function<R ()> configFunction; configFunction = boost::bind( configIter->second, config); returnValue= configFunction(); } return returnValue; } template<> std::map<std::string, bool (Config::* ) ()> ConfigReader::getConfigMap() { return boolConfigMap; } template<> std::map<std::string, int (Config::* ) ()> ConfigReader::getConfigMap() { return integerConfigMap; } template<> std::map<std::string, string (Config::* ) ()> ConfigReader::getConfigMap() { return stringConfigMap; } |
更新
它确实通过在地图中使用函数引用而不是boost :: function
来工作
除非成员函数是
1 | boolConfigMap["USE_NEW_VERSION"] = boost::bind(&Config::useNewVersion, someInstanceOfConfig); |
(非静态)成员函数指针与普通函数指针(或静态成员函数指针)不同的原因是成员函数具有隐藏的" zeroeth"参数,即内部的
此外,您对
1 | boost::function<bool()> |
这将处理所有返回
如果编译器足够新,则可能还需要更改为使用
编辑后显示成员函数指针:您还必须正确调用函数指针,例如
1 | (config.*configIter->second)(); |