我对整个工厂的实施还很陌生,结果也许我的问题听起来很错误,而且定义不明确。因此,我想简单地说一下,以便初始化派生类的分支,到目前为止,我已经设法对具有空构造函数的类进行了初始化。让我以两个小类介绍当前的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;
}
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工厂实现适用于我的代码。我知道在网上的其他地方有一些关于参数化构造函数的文章,但是他们并没有使我自己正确地理解如何做,这就是为什么我把这个文章归她。任何形式的帮助/建议将不胜感激!
如果您想要一个带有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")()};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句