2012-06-21 53 views
0
#include <boost/format.hpp> 
#include <boost/scoped_ptr.hpp> 
#include <stdexcept> 
#include <unordered_map> 
#include <functional> 
#define DECLARE_OBJECT(classname) namespace {core::declare_object<classname> __declarartion_#classname;} 

namespace core { 
    class dungeon; 
    class object; 
    typedef std::function<object* (dungeon *)> object_creator; 
    namespace library_type { 
    enum type { 
     landscape = 0, walker, foe, bonus,object = 42 
    }; 
    }; 
    struct library_error : public std::logic_error 
    { 
    explicit library_error(const std::string &what) : std::logic_error(what) {}; 
    }; 
    template <enum library_type::type type> 
    class library { 
    public: 
    static library<type> *instance() { 
     if (!m_instance) 
     m_instance = new library<type>(); 
     return m_instance; 
    } 
    template<typename T> 
    void add_object() { 
     boost::scoped_ptr<T> obj(T::create(nullptr)); 
     m_library.insert(obj->name(), T::create); 
    } 
    const object_creator& get_object(const std::string &key) { 
     auto lookup_iterator = m_library.find(key); 
     if (lookup_iterator == m_library.end()) 
     throw library_error(boost::format("Object creator for key `%1%' not found\n") % key); 
     return *lookup_iterator; 
    } 
    private: 
    library() {}; 
    static library<type> *m_instance; 
    std::unordered_map<std::string, object_creator> m_library; 
    }; 
    template <enum library_type::type type> 
    library<type>* library<type>::m_instance; 
    template <enum library_type::type type, typename T> 
    struct declare_object 
    { 
    declare_object() { 
     auto instance = library<type>::instance(); 
     auto method = instance->add_object<T>; 
     method(); 
    } 
    }; 
}; 
int main() 
{ 

} 

你好。這個簡單的C++ 0x代碼給我錯誤declare_object構造C++期望的主表達式編譯錯誤

example.cpp: In constructor ‘core::declare_object<type, T>::declare_object()’: 
example.cpp:52:43: error: expected primary-expression before ‘>’ token 
example.cpp:52:44: error: expected primary-expression before ‘;’ token 

我真的不知道我在哪裏錯了。也許清晰的觀點和建議? 對不起長列表。編輯:答案是auto method = instance -> template add_object<T>;。爲什麼你刪除了你的答案?

+0

'auto method = instance-> add_object ;'缺少圓括號。可能就是這樣。 – chris

+0

不,我想要指向方法。 – KAction

+0

噢,如果你用全名替換'auto',它會起作用嗎? – chris

回答

2

要獲得指向成員函數的指針,您需要遵循其他答案中的語法。

由於成員函數是另外一個模板,你需要指出這一點,因爲它是一個從屬名稱:

auto method = &library_type<type>::template add_object<T>; 

否則C++將在add_object<T>解析尖括號爲小於和大於運營商。

2
struct declare_object 
    { 
    declare_object() { 
     auto instance = library<type>::instance(); 
     auto method = &library<type>::template add_object<T>; 
     (instance->*method)(); 
    } 
    }; 
+0

+1,是的,額外的圓括號... – jxh

+1

嘿。花了血腥的年齡找出需要[FAQ]中的哪些位(http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.7)。我猜想這是他們宏觀建議的一點。建議您閱讀常見問題解答並執行該操作,如果您的代碼實際上比粘貼的內容更復雜:) – moonshadow

相關問題