C++ 删除具有类似工厂类的重复代码
我有以下代码:C++ 删除具有类似工厂类的重复代码,c++,templates,factory,C++,Templates,Factory,我有以下代码: struct Foo1 {} struct Foo1Helper {} // generated struct Foo2 {} struct Foo2Helper {} // generated struct Foo1Factory { Foo1* Create(){ return connect(); } protected: Foo1 *connect(); } // cpp file (important because i d
struct Foo1 {}
struct Foo1Helper {} // generated
struct Foo2 {}
struct Foo2Helper {} // generated
struct Foo1Factory {
Foo1* Create(){
return connect();
}
protected:
Foo1 *connect();
}
// cpp file (important because i don't want to have Foo1Helper in .h file)
Foo1* Foo1Factory::connect(){
return Foo1Helper::doSmth();
}
struct Foo2Factory {
Foo2* Create(){
return connect();
}
protected:
Foo2 *connect();
}
// cpp file (important because i don't want to have Foo2Helper in .h file)
Foo2* Foo2Factory::connect(){
return Foo2Helper::doSmth();
}
我有两个类Foo1和Foo2,它们都是在Foo1Helper和Foo2Helper类的帮助下使用工厂类创建的
我们的想法是,由于存在大量重复的代码,所以只需要一个工厂类,唯一的区别是在connect函数中调用的helper函数
注意:我想从头文件中隐藏帮助器类,因此必须在.cpp文件中实现连接功能。如果可以定义一些别名,则可以使用一个工厂;如果可以使用一些显式模板实例化,则可以在cpp中隐藏帮助器类。我不明白你为什么不这么做 在下文中,我假设您的工厂方法是静态的。如果它们不是,则可以很容易地用pimpl成语进行改编 头文件
问题是什么?这段代码有太多的错误,对我来说毫无意义。这个问题比这个问题更有意义,但仍然模糊不清。您有两个工厂,每个工厂都将对象创建直接指向不同的帮助器类,每个帮助器类都动态生成不同的对象类型。我想你可以在某个地方阻塞模板专门化或一些函数重载,但实际的最终目标仍然不完全清楚。迟早必须明确使用
Foo1Helper
和Foo2Helper
。
struct Foo1 { /* implementation */ };
struct Foo1Helper; // just declaration
struct Foo2 { /* implementation */ };
struct Foo2Helper; // just declaration
// a little helper
template <class Foo_main, class Helper>
struct Foo_trait
{
using Foo = Foo_main;
using FooHelper = Helper;
};
// this section can be easily generated
// if you have a lot of classes and feel particularly lazy
using Foo1_trait = Foo_trait<Foo1, Foo1Helper>;
using Foo2_trait = Foo_trait<Foo2, Foo2Helper>;
// just one Factory class
// no implementation exposed to the header
template <class Foo_trait>
struct FooFactory
{
using Foo = typename Foo_trait::Foo;
using FooHelper = typename Foo_trait::FooHelper;
static auto Create() -> Foo*;
};
struct Foo1Helper
{
static Foo1* doSmth()
{
static Foo1 f;
return &f;
}
};
struct Foo2Helper
{
static Foo2* doSmth()
{
static Foo2 f;
return &f;
}
};
template <class Foo_trait>
auto FooFactory<Foo_trait>::Create() -> Foo*
{
return FooHelper::doSmth();
}
// explicit template instantiation
// very important. Without this you get linker erorrs
// again very easy to generate
template struct FooFactory<Foo1_trait>;
template struct FooFactory<Foo2_trait>;
Foo1 f1 = FooFactory<Foo1_trait>::Create();
Foo2 f2 = FooFactory<Foo2_trait>::Create();
struct Foo1
{
using Helper = Foo1Helper;
};