Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c++ - How to remove the const from 'char const*'

It appears that std::remove_const isn't able to remove the const-ness of const char*. Consider the following code:

#include <iostream>
#include <type_traits>
#include <typeinfo>

template< typename T >
struct S
{
    static void foo( ) {
        std::cout << typeid(T).name() << std::endl;
        std::cout << typeid( std::remove_const<T>::type ).name() << std::endl;
    }
};


int main( )
{
    S<char const*>::foo();
}

Output of this program (on Visual Studio 2010):

char const *
char const *

And in gcc we have the readable output (code here):

PKc
PKc

I would hope to get char * on the second line of Microsoft compiler, and whatever (but different than 1st line) on gcc. What am I doing wrong? How do I turn char const* to char*?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

char const* is a pointer to a const char, but the pointer itself is not const. To remove the constness from the type being pointed to, you could do this:

std::add_pointer<typename std::remove_const<typename std::remove_pointer<T>::type>::type>::type

Or alternatively:

typename std::remove_const<typename std::remove_pointer<T>::type>::type*

We remove the pointer from const char* to get const char, then remove const to get char, then add the pointer back to get char*. Not particularly pretty. To test:

typedef const char * type_before;
std::cout << typeid(type_before).name() << std::endl;
typedef typename std::remove_const<typename std::remove_pointer<type_before>::type>::type* type_after;
std::cout << typeid(type_after).name() << std::endl;

With g++ on my system, this outputs:

PKc
Pc

This should give you a hint about what "PKc" means. P for pointer, c for char, and K for konst ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...