我有一个基类,代表一些(通用)硬件的处理程序,特定实例从中派生。处理程序接收的命令协议包括一个字符串,该字符串确定处理程序执行的功能。
我想使用构造字符串到函数指针的静态映射HashMap
(据我所知,这基本上类似于std::map
,所以这应该或多或少地适用于 JUCE 和std
)。我希望它是静态的,因为这个映射不会改变,而且我不想在每次实例化处理程序时都重新构建它(这可能会发生很多)。
//general hardware handler
class HandlerBase {
public:
// all command handlers take a BazCommand reference and return success
typedef bool (HandlerBase::* commandHandler)(BazCommand&);
// this is the mapping of String to the handler function that
// determines which function to run when getting a command
typedef HashMap<String, commandHandler> CmdList;
}
// handler for the Foomatic Barrifier 2000
class FoomaticHandler : public HandlerBase {
public:
//one of the Foomatic handler functions
bool barrify(BazCommand& cmd) {
return true;
}
static CmdList createCmdMapping() {
CmdList l;
l.set("bar", (commandHandler) &FoomaticHandler::barrify);
// add all Foomatic handler functions here
return l;
}
bool doCommand(BazCommand& cmd) {
String cmdString = cmd.getCmdString();
//execute correct function here
}
//this cmdList is static and shared betweeen all Foomatic handlers
static CmdList cmdList;
}
// set up the Foomatic command hashmap
FoomaticHandler::CmdList FoomaticHandler::cmdList =
FoomaticHandler::createCmdMapping();
但是,这种方法会产生很多错误。我尝试了几种替代安排。这个特定的产生:
../core/../../../juce/JuceLibraryCode/modules/juce_audio_basics/../juce_core/containers/juce_HashMap.h: In static member function ‘static HandlerBase::CmdList FoomaticHandler::createCmdMapping()’:
../core/../../../juce/JuceLibraryCode/modules/juce_audio_basics/../juce_core/containers/juce_HashMap.h:445:5: error: ‘juce::HashMap<KeyType, ValueType, HashFunctionToUse, TypeOfCriticalSectionToUse>::HashMap(const juce::HashMap<KeyType, ValueType, HashFunctionToUse, TypeOfCriticalSectionToUse>&) [with KeyType = juce::String, ValueType = bool (HandlerBase::*)(BazCommand&), HashFunctionToUse = juce::DefaultHashFunctions, TypeOfCriticalSectionToUse = juce::DummyCriticalSection, juce::HashMap<KeyType, ValueType, HashFunctionToUse, TypeOfCriticalSectionToUse> = juce::HashMap<juce::String, bool (HandlerBase::*)(BazCommand&)>]’ is private
FoomaticHandler.cpp:77:16: error: within this context
创建这样的静态字符串-> 成员函数映射的正确方法是什么?并且可以将createCmdList()
其制成纯虚拟来强制实施吗?