【问题标题】:How to extract type from empty templated container using decltype?如何使用 decltype 从空的模板容器中提取类型?
【发布时间】:2018-11-16 17:59:49
【问题描述】:

正确的decltype 语法从特定容器类中提取数据类型而不重复到value_type 成员类型定义是什么?

我尝试使用 decltype<std::declval<myContainerClass>[0]> 直接访问元素,但我意识到如果容器为空,它将无法正常工作。

【问题讨论】:

    标签: c++ templates types decltype


    【解决方案1】:

    你可以使用

    std::remove_reference_t<decltype(std::declval<Container>()[0])>
    

    decltype 中的所有内容都未计算,因此访问假设的空容器的元素 0 是 UB 并不重要。这只是从容器的operator[] 中提取必要的类型信息。您需要remove_reference,因为operator[] 可能返回一个左值引用。

    但是,这不适用于std::list&lt;T&gt; 等容器。相反,您可以使用:

    typename std::iterator_traits<typename Container::iterator>::value_type
    

    如果您不能假设Container::iterator 存在,您可以将typename Container::iterator 替换为decltype(std::declval&lt;Container&gt;().begin())

    【讨论】:

    • 你也可以通过结合这两种方法并取消引用begin()来避免使用iterator_traits
    • @ChristianRau 严格来说,返回::reference,这可能是一些奇怪的代理类型,而不是实际的引用。
    • 但是operator[] 也可以,不是吗?
    • 谢谢。但同样我不想假设存在value_type 成员,我也不确定begin() 是否存在于特定的非STL 容器中。
    猜你喜欢
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2013-09-23
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多