1

データ型からすべてのconst修飾子を削除するにはどうすればよいですか?

使ってみましstd::remove_cvたがうまくいきませんでした。

std::remove_cv< const char *>::type

と同じじゃないstd::remove_cv<char*>::typeですか?

ありがとう。

4

4 に答える 4

5

特性はすべてを正しく行っています:

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>>>;

はるかに読みやすい。

于 2012-12-16T16:13:48.070 に答える
1

これを行うための標準的な方法はありません。独自に作成する必要があります。

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;
};
于 2012-12-16T16:25:18.090 に答える
0

再帰的に実行します。スペシャライゼーションに一致してから、などT*を再適用します。*

于 2012-12-16T16:09:26.350 に答える
0

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

于 2012-12-16T16:23:38.523 に答える