2016-02-25 33 views
0

我試圖創建一個由int和指向成員函數的指針組成的地圖。創建成員函數指針的地圖

class Factory 
{ 
    public: 
    typedef nts::IComponent *(*createFunction)(const std::string &value); 
    Factory(); 
    ~Factory(); 
    nts::IComponent *createComponent(const std::string &type, const std::string &value); 
    private: 
    nts::IComponent *create4001(const std::string &value) const; 
    nts::IComponent *create4013(const std::string &value) const; 
    nts::IComponent *create4040(const std::string &value) const; 
    nts::IComponent *create4081(const std::string &value) const; 

    std::map<int, createFunction> map = {{4001, Factory::create4001}, 
             {4013, Factory::create4013}, 
             {4040, Factory::create4040}}; 
}; 

但是我有這個以下錯誤:

includes/Factory.hpp:24:68: error: could not convert ‘{{4001, ((Factory*)this)->Factory::create4001}, {4013, ((Factory*)this)->Factory::create4013}, {4040, ((Factory*)this)->Factory::create4040}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<int, nts::IComponent* (*)(const std::__cxx11::basic_string<char>&)>’ 
             {4040, Factory::create4040}}; 

有什麼想法?

+0

閱讀起來在使用它之前,您最喜歡的書中的主題。 'createFunction'不是成員函數指針的別名。它也缺少一個'const'限定符。 – LogicStuff

+1

嘗試'使用createFunction = nts :: IComponent *(const std :: string&);',然後使用'std :: map map;'。 –

+0

@KerrekSB相同的錯誤 –

回答

2

typedef爲指針(非靜態)成員函數如下:

typedef nts::IComponent *(Factory::*createFunction)(const std::string &value) const; 
//      ^^^^^^^            ^^^^^ 
//     nested name specifier        missing const 

優選方式:

using createFunction = nts::IComponent *(Factory::*)(const std::string &value) const; 

初始化您的地圖:

std::map<int, createFunction> map = {{4001, &Factory::create4001}, 
            {4013, &Factory::create4013}, 
            {4040, &Factory::create4040}}; 
//          ^
//      compiler would think you're trying to call 
//      a static function without an argument list