如何从'char const *'中删除const [英] How to remove the const from 'char const*'
问题描述
看起来std :: remove_const不能删除 const char *
的常数。考虑下面的代码:
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();
}
此程序的输出(在Visual Studio 2010上):
Output of this program (on Visual Studio 2010):
char const *
char const *
在gcc中,我们有可读输出(代码这里):
And in gcc we have the readable output (code here):
PKc
PKc
我希望在微软编译器的第二行获得 char *
,并且在gcc上获得任何(但不同于第一行)。我做错了什么?如何将 char const *
更改为 char *
?
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*
?
推荐答案
如果你想删除所有的const限定符,你需要一个解决方案递归地从所有级别中删除const:
If you want to remove all const qualifiers you need a solution that recursively removes const from all levels:
template<typename T> struct remove_all_const : std::remove_const<T> {};
template<typename T> struct remove_all_const<T*> {
typedef typename remove_all_const<T>::type *type;
};
template<typename T> struct remove_all_const<T * const> {
typedef typename remove_all_const<T>::type *type;
};
int main() {
std::cout << typeid(remove_all_const<int const * * const>::type).name() << '\n';
}
这篇关于如何从'char const *'中删除const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!