名前空間
変種
操作

std::is_const

From cppreference.com
< cpp‎ | types
 
 
メタプログラミングライブラリ
型特性
型のカテゴリ
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型のプロパティ
is_const
(C++11)
(C++11)
(C++14)
(C++11)(C++26で非推奨)
(C++11)(C++20まで*)
(C++11)(C++20で非推奨)
(C++11)
型特性定数
メタ関数
(C++17)
サポートされている操作
関係とプロパティクエリ
型の変更
(C++11)(C++11)(C++11)
型の変換
(C++11)(C++23で非推奨)
(C++11)(C++23で非推奨)
(C++11)
(C++11)(C++20まで*)(C++17)

(C++11)
(C++17)
コンパイル時有理数演算
コンパイル時整数シーケンス
 
ヘッダ <type_traits> で定義
template< class T >
struct is_const;
(C++11以降)

std::is_constUnaryTypeTrait です。

T が const 修飾された型(すなわち、const または const volatile)である場合、メンバ定数 valuetrue に等しくなります。それ以外の型の場合、valuefalse になります。

プログラムが std::is_const または std::is_const_v の特殊化を追加した場合、動作は未定義です。

目次

[編集] テンプレートパラメータ

T - チェックする型

[編集] ヘルパー変数テンプレート

template< class T >
constexpr bool is_const_v = is_const<T>::value;
(C++17以降)

std::integral_constant から継承

メンバ定数

value
[static]
T が const 修飾された型の場合は true、それ以外の場合は false
(公開静的メンバ定数)

メンバ関数

operator bool
オブジェクトを bool に変換し、value を返します。
(public member function)
operator()
(C++14)
value を返します。
(public member function)

メンバ型

定義
value_type bool
type std::integral_constant<bool, value>

[編集] 注記

T が参照型の場合、is_const<T>::value は常に false になります。参照型である可能性のある型を const 性についてチェックする適切な方法は、参照を削除することです:is_const<typename remove_reference<T>::type>

[編集] 実装候補

template<class T> struct is_const          : std::false_type {};
template<class T> struct is_const<const T> : std::true_type {};

[編集]

#include <type_traits>
 
static_assert(std::is_same_v<const int*, int const*>,
    "Remember, constness binds tightly inside pointers.");
static_assert(!std::is_const_v<int>);
static_assert(std::is_const_v<const int>);
static_assert(!std::is_const_v<int*>);
static_assert(std::is_const_v<int* const>,
    "Because the pointer itself can't be changed but the int pointed at can.");
static_assert(!std::is_const_v<const int*>,
    "Because the pointer itself can be changed but not the int pointed at.");
static_assert(!std::is_const_v<const int&>);
static_assert(std::is_const_v<std::remove_reference_t<const int&>>);
 
struct S
{
    void foo() const {}
    void bar() const {}
};
 
int main()
{
    // A const member function is const in a different way:
 
    static_assert(!std::is_const_v<decltype(&S::foo)>,
        "Because &S::foo is a pointer.");
 
    using S_mem_fun_ptr = void(S::*)() const;
 
    S_mem_fun_ptr sfp = &S::foo;
    sfp = &S::bar; // OK, can be re-pointed
    static_assert(!std::is_const_v<decltype(sfp)>,
        "Because sfp is the same pointer type and thus can be re-pointed.");
 
    const S_mem_fun_ptr csfp = &S::foo;
    // csfp = &S::bar; // Error
    static_assert(std::is_const_v<decltype(csfp)>,
        "Because csfp cannot be re-pointed.");
}

[編集] 関連項目

型がvolatile修飾されているかをチェックする
(クラステンプレート) [編集]
(C++17)
引数への const 参照を取得する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)