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

履歴 編集

function
<any>

std::any::コンストラクタ(C++17)

constexpr any() noexcept;                  // (1)
any(const any& other);                     // (2)
any(any&& other) noexcept;                 // (3)

template <class T>
any(T&& value);                            // (4)

template <class T, class... Args>
explicit any(in_place_type_t<T>,
             Args&&... args);              // (5)

template <class T, class U, class... Args>
explicit any(in_place_type_t<T>,
             initializer_list<U> il,
             Args&&... args);              // (6)

概要

  • (1) : 値を保持していない状態にする
  • (2) : コピーコンストラクタ
  • (3) : ムーブコンストラクタ
  • (4) : 任意の型Tの値value*thisにムーブして保持する
  • (5) : 任意の型Tのコンストラクタ引数args...をとり、コンストラクタ内部でT型オブジェクトを構築して保持する
  • (6) : 任意の型Tのコンストラクタ引数ilargs...をとり、コンストラクタ内部でT型オブジェクトを構築して保持する

テンプレートパラメータ制約

効果

  • (2) : other.has_value() == falseである場合、値を保持しないanyオブジェクトを構築する。そうでなければ、any(in_place<T>, any_cast<const T&>(other))と等価の効果をもつ
  • (3) : other.has_value() == falseである場合、値を保持しないanyオブジェクトを構築する。そうでなければ、otherが保持する値をthisにムーブする
  • (4) : std::forward<T>(value)をコンストラクタ引数として、型std::decay_t<T>のオブジェクトを直接構築して保持する
  • (5) : std::forward<Args>(value)...をコンストラクタ引数として、型std::decay_t<T>のオブジェクトを直接構築して保持する
  • (6) : ilstd::forward<Args>(value)...をコンストラクタ引数として、型std::decay_t<T>のオブジェクトを直接構築して保持する

事後条件

例外

  • (2) : otherが保持する型Tのオブジェクトの選択されたコンストラクタが、任意の例外を送出する可能性がある
  • (4), (5), (6) : 型std::decay_t<T>の選択されたコンストラクタが、任意の例外を送出する可能性がある

#include <any>
#include <string>
#include <vector>
#include <cassert>

int main()
{
  // (1)
  {
    std::any x;
    assert(!x.has_value());
  }

  // (2)
  {
    std::any a = 3;
    std::any b = a;

    assert(std::any_cast<int>(a) == 3);
    assert(std::any_cast<int>(b) == 3);
  }

  // (3)
  {
    std::any a = std::string("Hello");
    std::any b = std::move(a);

    assert(std::any_cast<std::string>(b) == "Hello");
  }

  // (4)
  {
    std::any a = 3;
    std::any b = std::string("Hello");

    assert(std::any_cast<int>(a) == 3);
    assert(std::any_cast<std::string>(b) == "Hello");
  }

  // (5)
  {
    std::any x {
      std::in_place_type<std::string>,
      3,
      'z'
    };

    assert(std::any_cast<std::string>(x) == "zzz");
  }

  // (6)
  {
    std::allocator<int> alloc;
    std::any x {
      std::in_place_type<std::vector<int>>,
      {3, 1, 4},
      alloc
    };

    const auto& vec = std::any_cast<const std::vector<int>&>(x);
    assert(vec[0] == 3);
    assert(vec[1] == 1);
    assert(vec[2] == 4);
  }
}

出力

バージョン

言語

  • C++17

処理系