[英]Why does `std::add_pointer`, adds a previously removed `const`?
Apologies if the title is a bit misleading.. Here's the situation.如果标题有点误导,我们深表歉意。情况就是这样。
Consider the following example:考虑以下示例:
template<typename T>
static std::string demangle_typename()
{
int status = 0;
return abi::__cxa_demangle(typeid(T).name(),nullptr,nullptr,&status);
}
void foo()
{
typedef const int* Type;
std::cout<< demangle_typename<Type>() <<std::endl; // type is: int const * <ok>
}
The type is int const *
类型是
int const *
Now, when I remove the const *
part using std::remove_pointer
and the I use std::add_pointer
to add the pointer back without the const
, the constness reappears.现在,当我使用
std::remove_pointer
删除const *
部分并且我使用std::add_pointer
在没有const
情况下添加指针时, const
重新出现。 Why?为什么?
void foo()
{
typedef const int* Type;
std::cout<< demangle_typename<Type>() <<std::endl; // type is: int const * <ok>
typedef typename std::remove_pointer<Type>::type rp_Type; // int
typedef typename std::add_pointer<rp_Type>::type p_Type; // int const * <???>
std::cout<< demangle_typename<p_Type>() <<std::endl; // type is: int const * <???>
}
To get the pointer without the const
I need to use std::remove_const
.要获得没有
const
的指针,我需要使用std::remove_const
。 But why is this needed, since std::remove_pointer
has already removed the const
?但是为什么需
std::remove_pointer
,因为std::remove_pointer
已经删除了const
?
void foo()
{
typedef const int* Type;
std::cout<< demangle_typename<Type>() <<std::endl; // type is: int const * <ok>
typedef typename std::remove_pointer<Type>::type rp_Type; // int
typedef typename std::remove_const<rp_Type>::type rc_Type; // int
typedef typename std::add_pointer<rc_Type>::type p_Type; // int*
std::cout<< demangle_typename<p_Type>() <<std::endl; // type is: int* <ok>
}
Online code example: https://rextester.com/YYE94945在线代码示例: https : //rextester.com/YYE94945
typeid
discards top-level cv-qualifiers on types. typeid
丢弃类型上的顶级 cv 限定符。 It doesn't see any difference between int
and const int
.它没有看到
int
和const int
之间的任何区别。
std::remove_pointer_t<const int *>
is const int
rather than int
, but const
doesn't get printed because of that. std::remove_pointer_t<const int *>
是const int
而不是int
,但因此不会打印const
。
Your demangle_typename
is not fit for purpose here: it won't show you top-level const
, so your results are not correct observations.您的
demangle_typename
不适合此处的用途:它不会向您显示顶级const
,因此您的结果不是正确的观察结果。 ( It can be fixed, though! ) (不过可以修复! )
rp_Type
is not int
but const int
. rp_Type
不是int
而是const int
。
Removing a pointer layer does not remove pointee constness.删除指针层不会删除指针对象的常量性。
So the const
is not "added";所以
const
不是“添加”的; it was never actually removed.它从未真正被移除。 You just don't observe it, with your solution, when it's top-level.
当它是顶级时,你只是没有观察它,用你的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.