dimanche 5 janvier 2020

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 *

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. 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. But why is this needed, since std::remove_pointer has already removed the 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

Aucun commentaire:

Enregistrer un commentaire