【问题标题】:Why is `std::remove_const` not removing the `const`-ness of a reference object when used with `decltype`? [duplicate]为什么 `std::remove_const` 在与 `decltype` 一起使用时不会删除引用对象的 `const`-ness? [复制]
【发布时间】:2019-02-10 03:33:33
【问题描述】:
#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&amp;int
也欢迎使用const_cast 的可能解决方案。


注意:由于我想对从对象中删除const 进行宏化处理;我用过decltype

【问题讨论】:

    标签: c++ c++11 constants decltype reference-type


    【解决方案1】:

    因为您使用的是文本替换宏而不是 typedef,所以您得到了const int&amp; x

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

    不可能更改引用的const-ness,因为 C++ 没有任何引用变异操作。

    如果您想删除最里面的constconst 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

    【讨论】:

    • 我试过remove_reference,但也没有用。可能是我没有尝试所有可能的选择。在这种情况下有什么帮助吗?
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多