关于增强中心工厂实现的静态方法

时间:2015-01-29 13:23:40

标签: c++ boost static-methods factory-pattern

我试图实现一个C ++工厂类,它也执行某些派生类的自注册。我的实现基于库:

http://arcticinteractive.com/2008/10/06/boost-centric-factory-pattern-implementation/

基于Boost库。为了简要介绍一下这个库,这里有一个简单的自我解释(希望)示例:

struct foo { virtual ~foo() {} };
struct bar : foo { bar(int i) { std::cout << "bar() " << i << "\n"; } };
struct baz : foo { baz(int i) { std::cout << "baz() " << i << "\n"; } };

...

typedef factory< foo*(int) > myfactory_t;

myfactory_t f;

// Register a default (operator new) creator function
// for an implementation type
register_new_ptr<bar>(f, "bar");
register_new_ptr<baz>(f, "baz");

// Create objects through the factory
foo* fooimpl1 = f["bar"](1234);
foo* fooimpl2 = f["baz"](4321);

我想要做的是委托每个班级使用静态方法将他们自己注册到工厂。这是代码:

animal.h

#pragma once
#include <cstring>
#include <iostream>
#include "factory.hpp"
#include "abstract_factory.hpp"
class zoo;

using namespace std;
using namespace boost::factory;

class animal{
  virtual const std::string do_sound() const = 0;
  std::string name_;
  int age_;
  zoo* myZoo_;

public:
  animal(const std::string& name, int age, zoo* myZoo) : name_(name), age_(age), myZoo_(myZoo)
  {}

  virtual ~animal() {}

  const std::string sound() const
  {
    return do_sound();
  }

  const std::string& name() const { return name_; }
  const int age() const { return age_; }
};

template <class T>
struct animalFactory{
    typedef factory< animal*(std::string&, int, zoo*) > myfactory_t;  
    static const myfactory_t* f;

    static bool registerAnimal(const std::string& animalname){
            return register_new_ptr<T>(&f, animalname);
    };
};

当我尝试注册一个类:

crocodile.cpp

#include "crocodile.h"

bool r = animalFactory<crocodile>::registerAnimal("crocodile");

我从visual studio 2012收到错误:

animal.h(41): error C2893: Failed to specialize function template 'bool boost::factory::register_new_ptr(Factory &,Factory::id_param_type)'

有人可以帮我理解这里发生了什么吗?非常感谢!

0 个答案:

没有答案
相关问题