定义遍历函数的const和非const版本
defining const and non-const version of traversal function
我有一个类似于列表的数据结构:
template<typename T>
struct node {
T val;
unique_ptr<node<T>> next;
};
和一个简单遍历函数:
template<typename T, typename UnaryOp>
void traverse(node<T>& list, UnaryOp op) {
node<T>* current = &list;
while(current) {
op(*current);
current = current->next.get();
}
我现在需要一个 版本的const
和non-const
traverse
函数,根据上下文接受const node<T>& list
或node<T>& list
,最好避免代码重复。这是如何实现的呢?
一个可能的解决方案是创建一个静态模板函数,将*this
作为转发引用:
class node
{
private:
template <typename TSelf>
static void traverse_impl(TSelf& self, node<T>& list, UnaryOp op)
{
node<T>* current = &list;
while(current)
{
op(*current);
current = current->next.get();
}
}
public:
void traverse(node<T>& list, UnaryOp op)
{
traverse_impl(*this, list, op);
}
void traverse(node<T>& list, UnaryOp op) const
{
traverse_impl(*this, list, op);
}
};
这是因为模板参数演绎规则——简而言之,TSelf
将接受const
和非const
引用。
如果需要访问traverse_impl
中的this
成员,则使用self.member
。
此外,您可以使用std::conditional
或traverse_impl
中的类似工具来执行不同的操作,具体取决于TSelf
的const
-ness。您还可以使用转发引用(TSelf&&
),并处理由于引用限定符和完美转发而移动this
的情况。
相关文章:
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 如何避免重复的const和非const虚拟函数?是否可以
- 避免使用 auto 关键字从字面上复制 const 和非 const 的代码?
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 返回一个 const 和非 const 包装器对象
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- 为什么BOOST.RANGE RANGE_BEGIN/END FREE功能对const和非const引用都重载
- Const和非常量函子
- 如何删除抽象类中类似的 const 和非 const 成员函数之间的代码重复
- 同一函数的const和非const版本——反模式
- 避免在const和非const成员函数中重复代码
- c++中返回引用的重载const和非const类方法
- 公开begin()和end()的const和非const版本,以使用智能指针迭代成员向量
- 树的const和非const版本的访问模式
- 应用于const和非const对象的引用返回方法
- 如何专门化const和非const容器的模板
- 定义遍历函数的const和非const版本
- 宏解决方案的重复,const和非const, getter
- Range-v3:使用view_facade来同时提供const和非const迭代器
- 不能使用操作符重载比较const和非const模板类型