c++ - 为什么 `std::remove_const` 在与 `const` 一起使用时不删除引用对象的 `decltype` -ness?

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

<分区>

#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

最佳答案

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

const int& 不是 const 类型,因此 remove_const 什么都不做。

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

如果你想删除最里面的 const(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

关于c++ - 为什么 `std::remove_const` 在与 `const` 一起使用时不删除引用对象的 `decltype` -ness?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613112/

相关文章:

c++ - 根据运行时决策组合不同的迭代器

c++ - 将 mysql 包含到 cmake 中

c++ - 强制在基类之前构造成员变量

c - 关于C数据类型和常量的问题

c++ - 无法从 Windows 7 访问 Linux UDP 服务器

c++11 - cgo 不包含 CXXFLAGS

c++ - 如何将特征功能委托(delegate)给类(class)成员?

c++ - 使用初始化列表初始化模板变量

python - 定义我自己的 None-like Python 常量

c - C中常量指针的奇怪行为