c++ - 为什么 `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
。
解决方案
因为您使用了文本替换宏而不是 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;
推荐阅读
- java - 我可以在休眠中引用 2 个具有相同列的不同实体吗?
- javascript - JavaScript 函数 - 从同一脚本调用
- c++ - 使用 Code::Blocks (C++) 在 Windows 10 上安装 FFTW3 库
- c# - 在 C# 中创建多层 DataGridView
- c++ - 为什么 std::function 可以隐式转换为具有更多参数的 std::function?
- authentication - OAuth2的注册过程
- spring - 无论任何语言环境如何,我如何保持固定的标准日期格式
- java - Android 未捕获相机内容视图 - 仅黑屏 - Android 10
- sql - 有没有办法以 hh:mm 格式显示时间
- python-3.x - 使用 Python 基于列表规范化单位/替换子字符串