C++17 中的通用工厂机制

Generic factory mechanism in C++17

本文关键字:工厂 机制 C++17      更新时间:2023-10-16

我想为一组派生类实现一个通用工厂机制,它不仅允许我通用地实现一个工厂函数来创建该类的对象,而且还允许其他模板类的创建者将派生类之一作为模板参数。

理想情况下,解决方案仅使用 C++17 个功能(无依赖项)。

考虑这个例子

#include <iostream>
#include <string>
#include <memory>
struct Foo {
virtual ~Foo() = default;
virtual void hello() = 0;
};
struct FooA: Foo { 
static constexpr char const* name = "A";
void hello() override { std::cout << "Hello " << name << std::endl; }
};
struct FooB: Foo { 
static constexpr char const* name = "B";
void hello() override { std::cout << "Hello " << name << std::endl; }
};
struct FooC: Foo { 
static constexpr char const* name = "C";
void hello() override { std::cout << "Hello " << name << std::endl; }
};
struct BarInterface {
virtual ~BarInterface() = default;
virtual void world() = 0;
};
template <class T>
struct Bar: BarInterface {
void world() { std::cout << "World " << T::name << std::endl; }
};
std::unique_ptr<Foo> foo_factory(const std::string& name) {
if (name == FooA::name) {
return std::make_unique<FooA>();
} else if (name == FooB::name) {
return std::make_unique<FooB>();
} else if (name == FooC::name) {
return std::make_unique<FooC>();
} else {
return {};
}
}
std::unique_ptr<BarInterface> bar_factory(const std::string& foo_name) {
if (foo_name == FooA::name) {
return std::make_unique<Bar<FooA>>();
} else if (foo_name == FooB::name) {
return std::make_unique<Bar<FooB>>();
} else if (foo_name == FooC::name) {
return std::make_unique<Bar<FooC>>();
} else {
return {};
}
}
int main()
{
auto foo = foo_factory("A");
foo->hello();
auto bar = bar_factory("C");
bar->world();
}

运行它

我正在寻找一种机制,该机制允许我在不列出所有类的情况下实现foo_factorybar_factory,这样一旦我添加例如FooD作为额外的派生类,就不需要更新它们。 理想情况下,不同的 Foo 衍生品会以某种方式"自我注册",但将它们全部列在一个中心位置也是可以接受的。

编辑:

基于评论/答案的一些澄清:

  • 在我的例子中,有必要用(类似)字符串调用工厂,因为工厂的调用者使用Foo/BarInterface的多态性,即他们不知道具体的派生类。另一方面,在 Bar 中,我们希望使用派生的 Foo 类的模板方法并促进内联,这就是为什么我们确实需要模板派生的Bar类(而不是通过一些基类接口访问 Foo 对象)。
  • 我们可以
  • 假设所有派生的Foo类都是在一个地方定义的(因此,如有必要,我们可以在同一地方列出所有类别的手动注册)。但是,他们不知道Bar的存在,实际上我们有多个不同的类,例如BarInterfaceBar。因此,我们不能创建 Bar 的"构造函数对象"并将它们保存在映射中,就像我们可以为foo_factory执行此操作一样。我认为需要的是所有派生的 Foo 类型的某种"编译时映射"(或列表),以便在定义bar_factory时,编译器可以迭代它们,但我不知道该怎么做......

编辑2:

在讨论期间证明相关的其他约束:

模板
  • 和模板模板:Foo 实际上是模板(具有单个类参数),Bar 是将具体的 Foo 作为模板参数的模板模板。Foo模板没有专用化,并且都具有相同的"名称",因此查询任何具体类型都可以。特别是SpecificFoo<double>::name始终有效。@Julius的回答已经扩展以促进这一点。对于@Yakk来说,同样的事情可能也可以完成(但我需要一些时间来详细弄清楚)。
  • 灵活的 Bar 工厂
  • 代码:Bar 的工厂不仅仅是调用构造函数。它还传递一些参数并执行一些类型转换(特别是,它可能具有应dynamic_cast到相应的具体派生 Foo 的 Foo 引用)。因此,允许在定义bar_factory期间内联编写此代码的解决方案对我来说似乎是最具可读性的。@Julius的答案在这里效果很好,即使带有元组的循环代码有点冗长。
  • 使列出 Foos 的"单一位置"更加简单:从到目前为止的答案来看,我相信对我来说要走的方法是拥有一个 foo 类型的编译时列表和迭代它们的方法。有两个答案可以在一个中心位置定义 Foo 类型(或模板)的列表(使用types模板或元组),这已经很棒了。但是,由于其他原因,我已经在同一个中心位置有一个宏调用列表,每个 foo 一个,例如DECLARE_FOO(FooA, "A") DECLARE_FOO(FooB, "B") ....FooTypes的声明是否可以以某种方式利用这一点,这样我就不必再次列出它们了?我想这样的类型列表不能迭代声明(附加到已经存在的列表中),或者可以吗?如果没有这个,也许有一些宏观魔法是可能的。也许总是重新定义并因此附加到DECLARE_FOO调用中的预处理器列表,然后最后一些"迭代循环"来定义FooTypes类型列表。IIRC 提升预处理器具有循环列表的功能(尽管我不想要升压依赖项)。

对于更多的context,你可以考虑不同的Foo和它的模板参数,类似于Eigen::Matrix<Scalar>和Bar是与Ceres一起使用的成本函子。条形图工厂将ceres::AutoDiffCostFunction<CostFunctor<SpecificFoo>, ...>等对象作为ceres::CostFunction*指针返回。

编辑3:

根据@Julius的回答,我创建了一个解决方案,该解决方案适用于作为模板和模板模板的条形图。我怀疑可以使用可变参数可变参数模板模板将bar_tmpl_factorybar_ttmpl_factory统一到一个函数中(这是一回事吗?

运行它

待办事项:

  • 结合bar_tmpl_factorybar_ttmpl_factory
  • 从上面Making the "single place" listing the Foos even simpler的点
  • 也许用 @Yakk 的types模板替换元组的使用(但在某种程度上,可以在所有 foo 类型的循环调用站点内联定义 creator 函数)。

我认为回答了这个问题,如果有的话,上述几点应该是单独的问题。

template<class...Ts>struct types_t {};
template<class...Ts>constexpr types_t<Ts...> types{};

这使我们能够使用类型包,而无需元组的开销。

template<class T>
struct tag_t { using type=T;
template<class...Ts>
constexpr decltype(auto) operator()(Ts&&...ts)const {
return T{}(std::forward<Ts>(ts)...);
}
};
template<class T>
constexpr tag_t<T> tag{};

这使我们能够将类型作为值来处理。

现在,类型标记映射是一个接受类型标记并返回另一个类型标记的函数。

template<template<class...>class Z>
struct template_tag_map {
template<class In>
constexpr decltype(auto) operator()(In in_tag)const{
return tag< Z< typename decltype(in_tag)::type > >;
}
};

这需要一个模板类型映射,并将其变成一个标记映射。

template<class R=void, class Test, class Op, class T0 >
R type_switch( Test&&, Op&& op, T0&&t0 ) {
return static_cast<R>(op(std::forward<T0>(t0)));
}
template<class R=void, class Test, class Op, class T0, class...Ts >
auto type_switch( Test&& test, Op&& op, T0&& t0, Ts&&...ts )
{
if (test(t0)) return static_cast<R>(op(std::forward<T0>(t0)));
return type_switch<R>( test, op, std::forward<Ts>(ts)... );
}

这让我们可以在一堆类型上测试条件,并在"成功"的类型上运行操作。

template<class R, class maker_map, class types>
struct named_factory_t;
template<class R, class maker_map, class...Ts>
struct named_factory_t<R, maker_map, types_t<Ts...>>
{
template<class... Args>
auto operator()( std::string_view sv, Args&&... args ) const {
return type_switch<R>(
[&sv](auto tag) { return decltype(tag)::type::name == sv; },
[&](auto tag) { return maker_map{}(tag)(std::forward<Args>(args)...); },
tag<Ts>...
);
}
};

现在我们要创建某个模板类的共享指针。

struct shared_ptr_maker {
template<class Tag>
constexpr auto operator()(Tag ttag) {
using T=typename decltype(ttag)::type;
return [](auto&&...args){ return std::make_shared<T>(decltype(args)(args)...); };
}
};

因此,这使得共享指针被赋予一种类型。

template<class Second, class First>
struct compose {
template<class...Args>
constexpr decltype(auto) operator()(Args&&...args) const {
return Second{}(First{}( std::forward<Args>(args)... ));
}
};

现在我们可以在编译时编写函数对象。

接下来连接起来。

using Foos = types_t<FooA, FooB, FooC>;
constexpr named_factory_t<std::shared_ptr<Foo>, shared_ptr_maker, Foos> make_foos;
constexpr named_factory_t<std::shared_ptr<BarInterface>, compose< shared_ptr_maker, template_tag_map<Bar> >, Foos> make_bars;

和完成。

最初的设计实际上是带有lambda的c ++ 20,而不是那些用于shared_ptr_maker等的struct

make_foosmake_bars的运行时状态均为零。

我认为需要的是某种"编译时映射"(或列表) 所有派生的 Foo 类型,以便在定义bar_factory时, 编译器可以迭代它们,但我不知道该怎么做......

这是一个基本选项:

#include <cassert>
#include <tuple>
#include <utility>
#include "foo_and_bar_without_factories.hpp"
////////////////////////////////////////////////////////////////////////////////
template<std::size_t... indices, class LoopBody>
void loop_impl(std::index_sequence<indices...>, LoopBody&& loop_body) {
(loop_body(std::integral_constant<std::size_t, indices>{}), ...);
}
template<std::size_t N, class LoopBody>
void loop(LoopBody&& loop_body) {
loop_impl(std::make_index_sequence<N>{}, std::forward<LoopBody>(loop_body));
}
////////////////////////////////////////////////////////////////////////////////
using FooTypes = std::tuple<FooA, FooB, FooC>;// single registration
std::unique_ptr<Foo> foo_factory(const std::string& name) {
std::unique_ptr<Foo> ret{};
constexpr std::size_t foo_count = std::tuple_size<FooTypes>{};
loop<foo_count>([&] (auto i) {// `i` is an std::integral_constant
using SpecificFoo = std::tuple_element_t<i, FooTypes>;
if(name == SpecificFoo::name) {
assert(!ret && "TODO: check for unique names at compile time?");
ret = std::make_unique<SpecificFoo>();
}
});
return ret;
}
std::unique_ptr<BarInterface> bar_factory(const std::string& name) {
std::unique_ptr<BarInterface> ret{};
constexpr std::size_t foo_count = std::tuple_size<FooTypes>{};
loop<foo_count>([&] (auto i) {// `i` is an std::integral_constant
using SpecificFoo = std::tuple_element_t<i, FooTypes>;
if(name == SpecificFoo::name) {
assert(!ret && "TODO: check for unique names at compile time?");
ret = std::make_unique< Bar<SpecificFoo> >();
}
});
return ret;
}

编写如下所示的泛型工厂,允许在类站点注册:

template <typename Base>
class Factory {
public:
template <typename T>
static bool Register(const char * name) {
get_mapping()[name] = [] { return std::make_unique<T>(); };
return true;
}
static std::unique_ptr<Base> factory(const std::string & name) {
auto it = get_mapping().find(name);
if (it == get_mapping().end())
return {};
else
return it->second();
}
private:
static std::map<std::string, std::function<std::unique_ptr<Base>()>> & get_mapping() {
static std::map<std::string, std::function<std::unique_ptr<Base>()>> mapping;
return mapping;
}
};

然后像这样使用它:

struct FooA: Foo {
static constexpr char const* name = "A";
inline static const bool is_registered = Factory<Foo>::Register<FooA>(name);
inline static const bool is_registered_bar = Factory<BarInterface>::Register<Bar<FooA>>(name);
void hello() override { std::cout << "Hello " << name << std::endl; }
};

std::unique_ptr<Foo> foo_factory(const std::string& name) {
return Factory<Foo>::factory(name);
}

注意:无法保证该类将被注册。如果没有其他依赖项,编译器可能会决定不包含翻译单元。最好简单地将所有类注册在一个中心位置。另请注意,自注册实现依赖于内联变量 (C++17)。它不是一个强依赖,可以通过在标头中声明布尔值并在 CPP 中定义它们来摆脱它(这使得自注册更丑陋,更容易注册失败)。

编辑

  1. 与其他答案相比,此答案的缺点是它在启动期间而不是在编译期间执行注册。另一方面,这使得代码更简单。
  2. 上面的示例假定Bar<T>的定义移到Foo之上。如果这是不可能的,那么注册可以在 cpp 中的初始化函数中完成:

    // If possible, put at the header file and uncomment:
    // inline
    const bool barInterfaceInitialized = [] {
    Factory<Foo>::Register<FooA>(FooA::name);
    Factory<Foo>::Register<FooB>(FooB::name);
    Factory<Foo>::Register<FooC>(FooC::name);
    Factory<BarInterface>::Register<Bar<FooA>>(FooA::name);
    Factory<BarInterface>::Register<Bar<FooB>>(FooB::name);
    Factory<BarInterface>::Register<Bar<FooC>>(FooC::name);
    return true;
    }();
    

在 C++17 中,我们可以应用 fold 表达式来简化生成函数的存储过程std::make_unique<FooA>()std::make_unique<FooB>()等在本例中到工厂类中。


为了方便起见,我们定义以下类型别名Generator,它描述了每个生成函数[](){ return std::make_unique<T>(); }的类型:

template<typename T>
using Generator = std::function<std::unique_ptr<T>(void)>;

接下来,我们定义以下相当通用的函子createFactory,它将每个工厂作为哈希映射std::unordered_map返回。 在这里,我使用逗号运算符应用折叠表达式。 例如,createFactory<BarInterface, Bar, std::tuple<FooA, FooB, FooC>>()()返回与函数bar_factory对应的哈希映射:

template<typename BaseI, template<typename> typename I, typename T>
void inserter(std::unordered_map<std::string_view, Generator<BaseI>>& map)
{
map.emplace(T::name, [](){ return std::make_unique<I<T>>(); });
}
template<typename BaseI, template<typename> class I, typename T>
struct createFactory {};
template<typename BaseI, template<typename> class I, typename... Ts>
struct createFactory<BaseI, I, std::tuple<Ts...>>
{
auto operator()()
{
std::unordered_map<std::string_view, Generator<BaseI>> map;
(inserter<BaseI, I, Ts>(map), ...);

return map;
}
};

这个函子使我们能够在一个中心位置列出FooA, FooB, FooC, ...,如下所示:

演示(我还在基类中添加了虚拟析构函数)

template<typename T>
using NonInterface = T;
// This can be written in one central place.
using FooTypes = std::tuple<FooA, FooB, FooC>;
int main()
{    
const auto foo_factory = createFactory<Foo, NonInterface, FooTypes>()();
const auto foo = foo_factory.find("A");
if(foo != foo_factory.cend()){
foo->second()->hello();
}

const auto bar_factory = createFactory<BarInterface, Bar, FooTypes>()();
const auto bar = bar_factory.find("C");
if(bar != bar_factory.cend()){
bar->second()->world();
}

return 0;
}