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

标签 c++ boost constructor factory

我对整个工厂的实现相当陌生,因此我的问题可能听起来是错误的并且定义不明确。 因此,简单地说,我希望有一个 boost factoty 来初始化一个 banch fo 派生类,到目前为止,我已经成功地为具有空构造函数的类做到了这一点。让我介绍一下我当前的两个小类的 boost 工厂实现:

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;
}

派生.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_ */

派生.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 工厂实现适用于我的代码。 我知道网上其他地方有一些关于参数化构造函数的帖子,但他们没能让我正确理解如何自己做这件事,这就是我给她发这篇文章的原因。 任何形式的帮助/建议将不胜感激!

最佳答案

如果你想要一个带有 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

关于c++ - 使用 boost 工厂在构造函数中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37137117/

相关文章:

Java - super 调用问题

java - 使用反射创建新对象?

c++ - 如何创建两个模板版本以获取数组开始和结束(使用 T* 和 It)而不重复代码?

c++ - 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上?

c++ - 从句柄获取文件路径

boost - 使用boost进程库防止子进程继承父进程打开的TCP端口

c++ - 为什么使用 [] 运算符会导致编译器错误?

c++ - 如何使 boost::thread_group 更小,并在其线程中运行 boost::asio::io_service::run?

java - 日历构造函数 Java toString

c++ - 选择整数类型的大小有哪些好的准则?