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构造函数中给了我错误

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

我真的不知道我错在哪里。也许有清晰的观点和建议?很抱歉长时间列出。编辑:答案是auto method = instance -> template add_object<T>;。为什么你删除了你的答案?

4

2 回答 2

2
  struct declare_object
  {
    declare_object() {
      auto instance = library<type>::instance();
      auto method = &library<type>::template add_object<T>;
      (instance->*method)();
    }
  };
于 2012-06-21T15:42:32.877 回答
2

要获得指向成员函数的指针,您需要遵循另一个答案中的语法。

由于成员函数也是一个模板,因此您需要指出这一点,因为它是一个从属名称:

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

否则,C++ 会将尖括号解析add_object<T>为小于和大于运算符。

于 2012-06-21T16:07:47.450 回答