首页 > 解决方案 > 为什么 `std::remove_const` 在与 `decltype` 一起使用时不会删除引用对象的 `const`-ness?

问题描述

#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


注意const:因为我想从一个对象中删除宏;我用过decltype

标签: c++c++11constantsdecltypereference-type

解决方案


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

const int&不是const类型,所以remove_const什么也不做。

不可能改变const引用的特性,因为 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


推荐阅读