在 C++ 中清理脏标志的聪明方法
Clever way to clean dirty flag in c++
我有这种情况,我试图为空间搜索结构公开一个标准API,其中构建结构的各种方法的输入数据是相同的,但搜索结构的构建方式是不同的。 我有基类上数据的设置器,以及派生类需要实现的纯虚拟 Build(( 方法来构造搜索结构。 下面是我的基类的样子
class SpatialSearch
{
public:
void SetData(Data data_)
{
this->data = data_;
this->dirty = true;
}
virtual void Build() = 0;
int search(Vec3 point)
{
if(dirty)
Build();
// Code to perform a search. I won't get into the
// nitty gritty of this, but this exists as a commom
// implementation on the base class for all the spatial
// search structures.
}
private :
Data data;
bool dirty;
}
因此,如果您注意到,每次调用搜索都会检查dirty
标志。 如果数据在上次后已更改,我将重建结构。 但是,Build 方法是在派生类上实现的,我需要一种方法来强制执行在执行 Build 方法后将此标志设置为false
的方法,而不仅仅是为编写派生类的人员留下一个准则,让他们在他们的"Build"方法中dirty = false
。
简而言之,我需要一种方法来确保用户在每次执行Build
方法后都设置了dirty = false
。
一种常见的方法是有一个垂直界面和一个水平界面(受保护和公共(。
"水平接口"是类的用户看到的接口,"垂直"接口是派生类实现者重写以添加功能的接口。
class SpatialSearch
{
public:
void SetData(Data data_)
{
this->data = data_;
this->dirty = true;
}
void Build() // no longer virtual
{
internal_build();
dirty = false;
}
int search(Vec3 point)
{
if(dirty)
internal_build();
// Code to perform a search. I won't get into the
// nitty gritty of this, but this exists as a commom
// implementation on the base class for all the spatial
// search structures.
}
protected:
virtual void internal_build() = 0; // implementers override this
private :
Data data;
bool dirty;
}
class SpecialSpatialSearch
: public SpatialSearch
{
protected:
void internal_build() override
{
// do the build without caring or knowing of the
// existence of the dirty flag
}
};
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 有没有一种方法可以只对斜杠的第一个实例应用fnmatch的FNM_PATHNAME标志
- 在 C++ 中清理脏标志的聪明方法
- 在线程中等待标志的最佳方法
- 为什么方法重载或枚举标志定义会触发 gcc7.2 编译器警告?
- C ++实现全局开关/标志以控制程序行为的最佳方法,而无需将类绑定到公共点
- 在C++中定义联合类型标志的最佳方法
- 在命令行程序中使用布尔值。找不到定义标志并检查它们是否在参数中的方法
- 使用 Doxygen 或类似方法记录枚举标志
- 清洁格式标志检查的方法
- C 杀死方法无需不断检查标志
- c++将标志添加到const方法中
- 检索自最后n秒以来设置标志的次数的有效方法
- 解码像 FAST 这样的数据协议的快速方法是什么,其中数据以字节为单位编码,并将位作为存在标志
- 设置携带标志的最快方法
- C++11检查标志的方法
- 是否有任何方法可以发现静态库是用-fPIC标志编译的?
- 有没有一种方法可以在输出二进制文件中存储clang编译时标志
- 将标志传递到方法的替代方法