【问题标题】:std::remove_reference or std::remove_cv first?首先是 std::remove_reference 还是 std::remove_cv?
【发布时间】:2013-06-22 02:56:10
【问题描述】:

如果我想提取 const 引用的类型(如 const double& 中的 double),我必须使用:

typename std::remove_cv<typename std::remove_reference<Type>::type>::type

或

typename std::remove_reference<typename std::remove_cv<Type>::type>::type

?

【问题讨论】:

    标签: c++ c++11 reference typetraits qualifiers


    【解决方案1】:

    首先使用remove_reference。 remove_cv 仅删除顶级限定符,在引用的情况下,没有任何(或被忽略)。

    显示差异的示例:

    #include <iostream>
    #include <type_traits>
    
    template<typename T>
    using Remove_cv_ref = std::remove_cv<typename std::remove_reference<T>::type>;
    
    template<typename T>
    using Remove_ref_cv = std::remove_reference<typename std::remove_cv<T>::type>;
    
    int main()
    {
        std::cout << std::is_same<typename Remove_cv_ref<const int&>::type, int>::value; // 1
        std::cout << std::is_same<typename Remove_ref_cv<const int&>::type, int>::value; // 0
    }
    

    Live demo.

    【讨论】:

      【解决方案2】:
      typename std::remove_cv<typename std::remove_reference<Type>::type>::type
      

      因为首先remove_reference&lt;const double&amp;&gt;::type 是const double,然后remove_cv&lt;const double&gt;::type 是double。

      但如果你有 C++11,请查看std::decay。

      【讨论】:

      • std::decay != Unqualified,两者的语义不同。
      • @Xeo 是的,你是对的。 (但是当T 既不是函数也不是数组(const double&amp; 就是这种情况)时,decay&lt;T&gt;::type 与remove_cv&lt;remove_reference&lt;T&gt;::type&gt;::type 相同。)(我还说“看看”,而不是“使用而是"^^)
      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 2013-12-29
      • 2020-09-15
      • 2013-06-04
      • 2017-12-23
      • 2020-12-23
      • 1970-01-01
      • 2012-03-07
      相关资源
      最近更新 更多