为什么'的std :: remove_const`用`decltype`使用时不删除参考对象的`const`的烦躁? [重复]

问题描述 投票:1回答:1

这个问题已经在这里有一个答案:

#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的;我已经使用decltype

c++ c++11 const decltype reference-type
1个回答
0
投票

由于您使用的文本替换宏,而不是一个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

© www.soinside.com 2019 - 2024. All rights reserved.