如何避免大多数成员功能相同的代码重复
How to avoid code duplication with mostly same member functions?
我已经实现了Michael和Scott队列(一个并发的无锁队列(,并且我遇到了出列操作代码重复的问题。这个问题通常不是关于队列算法本身,而是如何干净地实现几种函数变体它们大多具有相同的结构。我说的例子是:
bool dequeue() {
while(true) {
// [atomically load head, tail and head->next]
auto head = m_head.load(std::memory_order_acquire);
auto head_ptr = head.get();
auto tail = m_tail.load(std::memory_order_acquire);
auto next = head_ptr->next.load(std::memory_order_acquire);
auto next_ptr = next.get();
// Are head, tail, and next consistent?
if(head == m_head.load(std::memory_order_acquire)) {
// Is queue empty or tail falling behind?
if(head_ptr == tail.get()) {
// Is queue empty?
if(!next_ptr) {
return false;
}
// tail is falling behind. Try to advance it
m_tail.compare_exchange_strong(tail, tail(next_ptr));
} else if(next_ptr){
// [ above check is result free list interaction, not part of orginal algo ]
// [Read value from next_ptr->data]
// <<<variant of operation here>>>>
}
}
}
}
我已经计划实施各种操作来代替<<<variant of operation here>>>>
包括逻辑,如果其他代码退出循环等等,我希望避免复制主函数的主体。我应该如何继续?我至少使用C++14标准。背景故事是boost::lockfree::queue<>受到太多限制我想实现pop_if()
、compare_front()
、begin()
这样的操作除了CCD_ 5部分之外,共享相同的基本出列操作代码逻辑。
如果我理解正确,你可以创建一个带参数的泛型方法——一个函子
template <class Func>
bool dequeue_generic(Func func) {
....
func(next_ptr->data)
}
然后implement方法使用不同的函子来处理数据。
相关文章:
- 以下示例中如何避免代码复制?C++/库达
- 是否应该在模板化代码中完全避免const
- 避免在遍历 IShellItemArray 时出现代码重复
- 将函数作为参数传递以避免重复代码
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 继承、覆盖和虚函数,以避免重复代码
- 避免易失性和非易失性成员函数的代码重复
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 避免使用 std::any 编写相同的重复类型检查代码
- 在多个头文件中从接口声明被覆盖的函数时,如何避免重复代码?
- 是否可以避免在以下代码中复制/移动构造函数的需要?
- 简化代码以避免在顺时针旋转2D矩阵时出现TLE
- 如何避免大多数成员功能相同的代码重复
- 如何在这样的代码中避免 TLE?
- 如何组织耗时的代码以避免开销
- 如何重写此代码以避免使用全局
- 如何在C++代码中避免这些类型的内存泄漏
- 如何重构这段简单的代码以避免代码重复
- 任何人都可以修改以下代码以避免使用"if"吗?
- 是否可以更改此代码以避免使用C++lambda表达式