最終更新日時(UTC):
が更新

履歴 編集

class template
<type_traits>

std::is_default_constructible(C++11)

namespace std {
  template <class T>
  struct is_default_constructible;

  template <class T>
  inline constexpr bool is_default_constructible_v
    = is_default_constructible<T>::value;          // C++17
}

概要

Tデフォルト構築可能か調べる

要件

Tは完全型であるか、const/volatile修飾された(あるいはされていない)voidか、要素数不明の配列型でなければならない。

効果

is_default_constructibleは、型Tデフォルト構築可能であるならばtrue_typeから派生し、そうでなければfalse_typeから派生する。

is_constructible<T>::value == trueの時に、デフォルト構築可能であると判断される。

#include <type_traits>

struct s {
  s(int){}
  // デフォルトコンストラクタは暗黙に = delete されている。
  // そのためデフォルト構築できない。
};

static_assert(std::is_default_constructible<int>::value == true, "value == true, int is default constructible");
static_assert(std::is_same<std::is_default_constructible<int>::value_type, bool>::value, "value_type == bool");
static_assert(std::is_same<std::is_default_constructible<int>::type, std::true_type>::value, "type == true_type");
static_assert(std::is_default_constructible<int>() == true, "is_default_constructible<int>() == true");

static_assert(std::is_default_constructible<s>::value == false, "value == false, s is not default constructible");
static_assert(std::is_same<std::is_default_constructible<s>::value_type, bool>::value, "value_type == bool");
static_assert(std::is_same<std::is_default_constructible<s>::type, std::false_type>::value, "type == false_type");
static_assert(std::is_default_constructible<s>() == false, "is_default_constructible<s>() == false");

static_assert(std::is_default_constructible<double>::value == true, "double is default constructible");
static_assert(std::is_default_constructible<const int>::value == true, "const int is default constructible");
static_assert(std::is_default_constructible<int[1]>::value == true, "int[1] is default constructible");
static_assert(std::is_default_constructible<void*>::value == true, "void* is default constructible");

static_assert(std::is_default_constructible<int[]>::value == false, "int[] is not default constructible");
static_assert(std::is_default_constructible<void>::value == false, "void is not default constructible");
static_assert(std::is_default_constructible<int&>::value == false, "int& is not default constructible");
static_assert(std::is_default_constructible<int&&>::value == false, "int&& is not default constructible");
static_assert(std::is_default_constructible<int ()>::value == false, "int () is not default constructible");

int main(){}

出力

バージョン

言語

  • C++11

処理系

  • Clang: 3.0
  • GCC: 4.7.0
  • Visual C++: 2012, 2013, 2015
    • 2012~2013には、提案時の名前であるhas_default_constructorも存在する。
    • 2012~2013は、std::is_default_constructible<int[]>のような要素数の指定がない配列型において、誤ってtrue_typeになっている。has_default_constructorも同様である。

備考

上の例でコンパイラによってはエラーになる。Clang 3.0 は constexpr に対応していないためにエラーになる。operator bool は持っているので、実行時に用いることはできる。

参照