我对整个工厂的实现相当陌生,因此我的问题可能听起来是错误的并且定义不明确。 因此,简单地说,我希望有一个 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")()};
关于c++ - 使用 boost 工厂在构造函数中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37137117/