#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>;
。爲什麼你刪除了你的答案?
'auto method = instance-> add_object;'缺少圓括號。可能就是這樣。 –
chris
不,我想要指向方法。 – KAction
噢,如果你用全名替換'auto',它會起作用嗎? – chris