C++23中使用模板typedef是否会强制重复迭代器对象?Deducing this能否规避?
Deducing this 与迭代器代码重复问题
Deducing this 的核心作用之一,就是让成员函数能感知调用它的对象的 cvref(const/volatile/reference)属性,以此避免冗余的代码重复。
问题:使用 typedef 定义返回类型时,是否必须重复定义迭代器?
如果我们通过声明别名模板(typedef)来指定成员函数的返回类型,而非直接用 auto 推导,通常确实需要分别定义普通迭代器和常量迭代器两个独立的类:
template <typename T> struct const_list_iterator{ typedef const T& reference; typedef const T* pointer; reference operator*() const{/***/} pointer operator->() const{/***/} };
template <typename T> struct list_iterator{ typedef T& reference; typedef T* pointer; reference operator*(){/***/} pointer operator->(){/***/} };
这是因为两者的 reference 和 pointer 类型不同,成员函数的 const 修饰符也有区别,只能通过两个分开的类来实现对应的行为。
用 Deducing this + auto 返回:单个迭代器即可?
借助 C++23 的 Deducing this 特性,搭配 auto 作为返回类型,我们只需要定义一个迭代器类就能同时处理普通和常量场景:
template <typename T> struct list_iterator { template <typename itself> auto operator*(this itself&& self){/***/} template <typename itself> auto operator->(this itself&& self){/***/} };
在容器中使用时,普通版本和 const 版本的 begin() 都可以返回同一个迭代器类型:
template <typename T> struct list{ using iterator = list_iterator<T>; auto begin() -> iterator { return iterator(node->next); } auto begin() const -> iterator{ return iterator(node->next); } };
模板化的成员函数会根据调用时的 itself 类型(即迭代器对象自身的 cvref 属性),自动推导返回的引用/指针类型,无需拆分两个迭代器类。
结论
是的,使用 typedef 定义固定返回类型时,确实会强制我们重复定义普通迭代器和常量迭代器对象。而 Deducing this 特性通过让成员函数感知自身的 cvref 属性,配合 auto 推导返回类型,能彻底消除这种代码重复,只用一个迭代器类就能覆盖所有场景。
内容的提问来源于stack exchange,提问作者Aaron Chifwalo Shavesha
相关产品推荐
相关产品推荐

