データ型からすべてのconst修飾子を削除するにはどうすればよいですか?
使ってみましstd::remove_cv
たがうまくいきませんでした。
std::remove_cv< const char *>::type
と同じじゃないstd::remove_cv<char*>::type
ですか?
ありがとう。
特性はすべてを正しく行っています:
const char*
と同じでchar const*
あり、どちらもとchar* const
同じではありません。したがって、あなたの場合、ポインタでconst
はなく、ポインタです。そしてremove_const
(ある程度論理的に)外側のものだけを削除し、const
内側のものは削除しません。
const
ポインティの本質を本当に取り除きたい場合は、次のように行うことができます。
using T = char const*;
using NoConstT = std::add_pointer<std::remove_cv<std::remove_pointer<T>::type>::type>::type;
(std::add_pointer<T>::type
より単純なものを優先して削除することもできますがT*
…)
つまり、ポインタを削除し、ポインタのを削除してconst
、結果を再度ポインタにします。
実際、これはR. Martinho Fernandesの</a>優れたWheelsライブラリを使用する良い機会であり、このようなネストされた特性に便利なショートカットを提供します。
#include <wheels/meta.h++>
using namespace wheels;
…
using NoConstT = AddPointer<RemoveCv<RemovePointer<T>>>;
はるかに読みやすい。
これを行うための標準的な方法はありません。独自に作成する必要があります。
template<typename T> struct remove_const_recursive { typedef T type; };
template<typename T> struct remove_const_recursive<T const volatile> {
typedef typename remove_const_recursive<T>::type volatile type;
};
template<typename T> struct remove_const_recursive<T volatile> {
typedef typename remove_const_recursive<T>::type volatile type;
};
template<typename T> struct remove_const_recursive<T const> {
typedef typename remove_const_recursive<T>::type type;
};
template<typename T> struct remove_const_recursive<T&> {
typedef typename remove_const_recursive<T>::type& type;
};
template<typename T> struct remove_const_recursive<T*> {
typedef typename remove_const_recursive<T>::type* type;
};
再帰的に実行します。スペシャライゼーションに一致してから、などT*
を再適用します。*
type_traits
定数ポインタとconstを指すポインタの違いと、
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::is_same<std::remove_const<const char*>::type, char*>::value << '\n';
std::cout << std::is_same<std::remove_const<char* const>::type, char*>::value << '\n';
std::cout << std::is_same<std::add_pointer<std::remove_const<std::remove_pointer<const char*>::type>::type>::type, char*>::value << '\n';
return 0;
}
これは出力として与えます
0
1
1