#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
构造函数
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 :(得分:2)
struct declare_object
{
declare_object() {
auto instance = library<type>::instance();
auto method = &library<type>::template add_object<T>;
(instance->*method)();
}
};
答案 1 :(得分:2)
要获得指向成员函数的指针,您需要遵循其他答案中的语法。
由于成员函数还是一个模板,因此需要指明这一点,因为它是一个从属名称:
auto method = &library_type<type>::template add_object<T>;
否则C ++会将add_object<T>
中的尖括号解析为小于和大于运算符。