如何重构这个类模板以最小化锅炉板代码
how to refactor this class template to minimize boiler-plate code?
我最近开始使用boost mirror进行ORM反射,这样我就可以最大限度地减少与DB相关的锅炉板代码的数量。
下面列出了我遇到的一种模式。
由于即使对于Baz
,Bar
的代码看起来也是一样的,我想知道,有可能进一步折叠这个代码吗
如果getValues()
接口看起来相同,那就太好了,但相同的实现也可以存在于Foo
中。
#include <iostream>
template< typename T >
struct Foo
{
static std::ostream& GetValues_Worker( std::ostream& os, T const& t )
{
// do boost mirror reflection stuff here
return os;
}
};
struct Bar :
public Foo<Bar>
{
// REFACTOR IF POSSIBLE: this code will always look the same - even for Baz
std::ostream&
getValues( std::ostream& os ) const
{
return GetValues_Worker( os, *this );
}
};
struct Baz :
public Foo<Baz>
{
// REFACTOR IF POSSIBLE: looks the same as Bar
std::ostream&
getValues( std::ostream& os ) const
{
return GetValues_Worker( os, *this );
}
};
int main( int argc, char* argv[] )
{
Bar b;
std::cerr << b.getValues( std::cerr ) << std::endl;
}
答案
事实证明,ecatmur下面的答案在大多数情况下都有效。在我的具体情况下,我根据我的真实代码调整了他的解决方案,在四分之二的情况下都有效。在两个失败的案例中,它有点超出了我上面给出的米老鼠例子的范围。我能在SO中找到的解释编译时错误的最接近的解释可能是这篇文章。问题的关键似乎与Worker代码中发生的事情有关。在这两个失败的案例中,我根据从运行时反射得到的结果对子类的成员进行输出流式处理,结果是提升镜像。我认为这是不可推导上下文的情况。我仍然不明白为什么这两个失败案例中的解决方案能准确工作(为什么以虚拟方法的形式使用访问者可以绕过这个问题)。无论如何,我偶然发现了这种方法,并试图进一步减少代码(在这4种情况下),但在其中两种情况下,如果不遇到不可推导上下文问题,我就无法真正减少代码。
Bar::getValues
可以使用CRTP下变频移动到Foo<Bar>
:
template< typename T >
struct Foo
{
static std::ostream& GetValues_Worker( std::ostream& os, T const& t )
{
// do boost mirror reflection stuff here
return os;
}
std::ostream& getValues( std::ostream& os ) const
{
return GetValues_Worker( os, *static_cast<T const *>(this) );
}
};
在这一点上,您不妨将两种方法结合起来:
template< typename T >
struct Foo
{
std::ostream& getValues( std::ostream& os ) const
{
T const &t = *static_cast<T const *>(this);
// do boost mirror reflection stuff here
return os;
}
};
相关文章:
- 找到两对数字,使它们的乘积的绝对差最小化
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 超轻 - 如何最小化窗口
- 在C++中使用 GSL 最小化
- 在C++中最小化变量的范围
- 当只有一个线程主要使用该对象而其他线程很少使用它时,如何最小化该对象的互斥锁锁定?
- "最小化"按钮不会出现在 MFC 对话框中
- 从小于或等于某个 N 的数字列表中最小化或找到 n 个理想的子集和
- 如何排列二进制字符串以最小化它们之间的距离
- 最小化 C++ 中的内存使用
- 禁用 GPO 的空气抖动最小化
- 如何隐藏最大化和最小化按钮并在qml应用程序窗口中显示关闭按钮?
- 如何使用 stl 最小化 c++ 中所有打开的窗口
- 如何最小化嵌入式平台上的内存分配
- 可见程序或最小化程序时的过程ID更改
- 删除/最小化GIT合并冲突
- 如何重构这个类模板以最小化锅炉板代码
- 如何最小化模板代码
- 如何在下面的代码中最小化浮点运算
- 透明比较器代码最小化