繁体   English   中英

为什么不能将模板引用类型用作模板类型别名?

[英]Why can't a template reference type be used as a template typealias argument?

我目前正在为自定义集合样式类编写迭代器。 我有一个可变的迭代器类,可以很好地工作,但是我决定最好也实现一个const版本,该版本将阻止对要迭代其内容的对象的修改。 我决定避免使用单独的类和代码重复,方法是在网上发现使用条件输入的建议。

我以典型的C ++ 11方式定义了iterator_traits别名,该别名将允许代码共享和模板参数依赖的const或可变行为(ItemType是外部容器类上的模板参数):

template<bool Const = false>
class iterator {
public:
    using reference = std::conditional_t<Const, const ItemType &, ItemType &>;
    using pointer = std::conditional_t<Const, const ItemType *, ItemType *>;

    //Rest of the iterator_traits and some other typealiases

    ...

    template<bool _Const = Const>
    std::enable_if_t<_Const, value_type>
    operator*() const
    {
        //Return copy
    }
     //Non-const version
    template<bool _Const = Const>
    std::enable_if_t<!_Const, reference>
    operator*()
    {
        //Return modifiable reference type
    }
    ...
}

我决定尝试通过创建另一个像这样的模板类型别名来删除重复的std::conditional_t调用:

template<typename type>
using const_conditional = std::conditional_t<Const, const type, type>;

并将所有std::conditional_t<...>替换为const_conditional<some_type_here> 对于外部类模板参数ItemType类型,这似乎普遍适用,但是当外部类类型的类型是引用时,则不适用于外部类类型本身,例如const_conditional<MyCollection<ItemType> &> 编译后,编译器抱怨我放弃了限定符,这意味着未应用const ,因此我违反了const要求,但是用原始的std::conditional_t代码替换了我的自定义类型别名,并按预期方式进行编译和运行,我不知道为什么。

当然,我可以简单地返回到我最初使用的std::conditional_t调用,该调用工作正常,但它们似乎过时且重复,而且我不理解为什么我的自定义typealias失败。 在我的特定情况下,通过互联网进行搜索无法帮助我。 任何帮助将由衷的感谢。

ItemType&ItemType*本身就是类型,因此添加const限定符将分别产生ItemType& const (在这种情况下,由于模板参数替换而导致静默忽略const )和ItemType* const ,这与预期的const ItemType&const ItemType* 对于后者,您可以使用:

template <typename type>
using const_conditional = std::conditional_t<Const, const type, type>;
// ...

using reference = const_conditional<ItemType>&;
using pointer = const_conditional<ItemType>*;

演示


附带说明一下, _Const是保留标识符,所有其他标识符都以下划线开头,后跟一个大写字母。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM