代码之家  ›  专栏  ›  技术社区  ›  iammilind

为什么当“使用DECKTYPE”时,STD::ReaveWyconst不删除引用对象的“const”?[复制品]

  •  0
  • iammilind  · 技术社区  · 7 年前

    这个问题已经有了答案:

    #define T int
    int main ()
    {
      const T x = 2;
      // (1) -- type of `x` is compared with `T`
      static_assert(std::is_same<std::remove_const<decltype(x)>::type, T>::value, "Not same");
      // (2) -- type of `x` is compared with `const T`
      static_assert(std::is_same<std::remove_const<decltype(x)>::type, const T>::value, "Not same");
    }
    

    以上代码按预期工作。其中(1)通过,(2)失败。

    然而,它发生在另一个方面,即。(1)如果我做了以下更改,则失败和(2)通过:

    #define T int& // <--- added reference
    

    为什么会这样?

    类似的代码 decltype ,我们可以向代码中添加什么,以便(1)同时传递引用和非引用类型,即。 int& 和; int ?
    可能的解决方案 const_cast 也很受欢迎。


    注释 :因为我要宏FY删除 const 从一个物体;我用 解密 .

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ben Voigt    7 年前

    因为使用了文本替换宏而不是typedef,所以 const int& x .

    const int& 不是一个 const 类型,所以 remove_const 什么都不做。

    改变是不可能的 康斯特 -引用的正确性,因为C++没有任何引用的变异操作。

    如果你想移除最里面的 康斯特 (何处) const T 如果是这样的话:

    template <typename T>
    struct remove_deepest_const_impl { typedef T type; };
    
    template <typename T>
    struct remove_deepest_const_impl<const T> { typedef T type; };
    
    template <typename T>
    struct remove_deepest_const_impl<T*>
    { typedef typename remove_deepest_const_impl<T>::type* type; };
    
    template <typename T>
    struct remove_deepest_const_impl<T* const>
    { typedef typename remove_deepest_const_impl<T>::type* const type; };
    
    template <typename T>
    struct remove_deepest_const_impl<T&>
    { typedef typename remove_deepest_const_impl<T>::type& type; };
    
    template <typename T>
    struct remove_deepest_const_impl<T&&>
    { typedef typename remove_deepest_const_impl<T>::type&& type; };
    
    template <typename T> using remove_deepest_const
           = typename remove_deepest_const_impl<T>::type;
    

    演示: https://rextester.com/OUTIN28468

    推荐文章