使用boost工厂在构造函数中传递参数

时间:2016-05-10 11:24:11

标签: c++ boost constructor factory

我对整个工厂实施相当新,结果可能我的问题听起来不对,而且定义不明确。 因此,为了初始化一个banch fo派生类,我想用一些词来提供一个强大的事实,到目前为止,我已经设法为具有空构造函数的类做了这样的事情。让我介绍一下两个小班的目前的升级工厂实施:

Base.h:

#ifndef BASE_H_
#define BASE_H_

#include <vector>
#include <map>
#include "boost/function.hpp"

class base {

protected:
    typedef boost::function <base *()> basefactory;

public:
      base();
      virtual ~base();

     int a;

     static std::map<std::string,base::basefactory>& b_factory();

  };

#endif /* BASE_H_ */

Base.cpp:

#include "base.h"

base::base() {
   // TODO Auto-generated constructor stub
}

base::~base() {
  // TODO Auto-generated destructor stub
}

static std::map<std::string,base::basefactory>& base::b_factory()
{
  static std::map<std::string,base::basefactory>* ans =
  new std::map<std::string,base::basefactory>();
  return *ans;
}

Derived.h:

#ifndef DERIVED_H_
#define DERIVED_H_

#include "boost/function.hpp"
#include "boost/functional/factory.hpp"
#include <iostream>

#include "base.h"

class derived : public base {
     public:
         derived();
         virtual ~derived();

          int b;

          static class _init {
            public:
               _init() {
                       base::b_factory()["derived"] = boost::factory<derived*>();
                       }
           }_initializer;

 };

 #endif /* DERIVED_H_ */

Derived.cpp:

#include "derived.h"

derived::derived() {
    // TODO Auto-generated constructor stub
}

derived::~derived() {
    // TODO Auto-generated destructor stub
}

derived::_init derived::_initializer;

因此,上面提到的代码适用于类的空构造函数,但是我很不确定如何在基类和派生类构造函数需要接收参数的情况下修改代码。更具体地说,我想说我想要基础构造函数:

base(int alpha) { 
a = alpha;
}

还有派生的构造函数:

derived(int alpha, int beta) : base( alpha ) // in order to pass the argument alpha to the base class
{ 
    b = beta;
}

所以,如上所述,我真的不确定我需要做些什么修改才能设法让上面的boost工厂实现为我的代码工作。 我知道这里有一些帖子在其他地方的参数化构造函数,但他们没有设法让我正确理解如何自己做这个,这就是为什么我把这个帖子发给她。 任何形式的帮助/建议都将不胜感激!

1 个答案:

答案 0 :(得分:2)

如果你想要一个带2个参数的工厂,你可以这样做:

std::map<std::string, boost::function<base* (int, int)>> factories;
factories["derived"] = boost::bind(boost::factory<derived*>(), _1, _2);

std::unique_ptr<base> b{factories.at("derived")(42, 52)};

如果你想修改参数,你可以做

std::map<std::string, boost::function<base* ()>> factories;
factories["derived"] = boost::bind(boost::factory<derived*>(), 42, 52);
std::unique_ptr<base> b{factories.at("derived")()};

Demo