我有两个几乎相同的类,实际上每个成员函数都是相同的,每个成员都是相同的,每个成员函数都做完全相同的事情。这些类之间的唯一区别是我可以定义其类型的变量的方式:
AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;
以下是它们的标题:
template<double&& Factor>
struct AllocFactorLinear;
template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific
我的问题是如何从这些类中重构这些函数,使我只拥有一组函数而不是两个函数相同函数的集合。
I have two almost identical classes, in fact every member function is identical, every member is identical, every member function does exactly the same thing. The only difference between those classes is the way I can define variable of their type:
AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;
Here are headers for them:
template<double&& Factor>
struct AllocFactorLinear;
template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific
My question is how can I refactor those functions out of those classes that would allow me to have just one set of functions and not two sets of identical functions.
发布评论
评论(4)
提取第三个类中的所有常见行为(为了清楚起见,我在答案中省略了模板参数):
然后我看到两个选择(至少从我的角度来看,它们几乎是等效的):
AllocFactorLinear
和AllocFactorScientific
从此类私有继承,并使用using将您希望公开的成员函数引入范围内
指令:聚合
AllocFactorLinear
和AllocFactorScientific
中的实现类,并将所有调用转发到私有实现:我个人会选择第一个解决方案。
Extract all the common behavior in a third class (I'm omitting the template arguments in my answer for the sake of clarity) :
I then see two choices (which are, from my point of view at least, pretty much equivalent) :
Make
AllocFactorLinear
andAllocFactorScientific
inherit privately from this class, and bring the member functions you wish to expose in scope with ausing
directives :Aggregate the implementation class in
AllocFactorLinear
andAllocFactorScientific
and forward all the calls to the private implementation :I would personally go for the first solution.
也许尝试使用此函数创建一些基类,并使用该基类的继承模板来执行这两个类。
Maybe try with creating some base class with this functions and do this 2 classes with templates on inheritance of this base class.
为什么为此使用模板类?
你不能使用一个带有两个不同构造函数的非模板类吗?
Why do you use a templated class for this?
Couldnt you use a untemplated class with 2 different constructors?
我认为它会是这样的:
然后你可以有
Type
,例如:并且:
你可以使用
AllocFactor创建
以及与AllocFactor
>FactorScientificConfig
相对应的内容。然后,您可以使用静态成员函数返回为这两个类计算的值,以便AllocFactor
可以使用T::value()
作为报告的值通过配置类。I think it would be something like:
and then you can have
Type
, for example:and:
You can create the
AllocFactor
usingAllocFactor<LinearConfig<1.2>>
and the corresponding with theFactorScientificConfig
. Then you can use the static member function to return the value calculated for both the classes, so thatAllocFactor<T>
can useT::value()
as the value reported by the config class.