std::any:: emplace
From cppreference.net
|
template
<
class
ValueType,
class
...
Args
>
std:: decay_t < ValueType > & emplace ( Args && ... args ) ; |
(1) | (C++17以降) |
|
template
<
class
ValueType,
class
U,
class
...
Args
>
std:: decay_t < ValueType > & emplace ( std:: initializer_list < U > il, Args && ... args ) ; |
(2) | (C++17以降) |
含まれるオブジェクトを、引数から構築された型 std:: decay_t < ValueType > のオブジェクトに変更します。
まず、現在格納されているオブジェクト(存在する場合)を reset() によって破棄し、その後:
1)
std::
decay_t
<
ValueType
>
型のオブジェクトを構築し、
直接非リスト初期化
によって
std::
forward
<
Args
>
(
args
)
...
から格納オブジェクトとして初期化します。
- このオーバーロードは、 std:: is_constructible_v < std:: decay_t < ValueType > , Args... > と std:: is_copy_constructible_v < std:: decay_t < ValueType >> の両方が true である場合にのみ、オーバーロード解決に参加します。
2)
std::
decay_t
<
ValueType
>
型のオブジェクトを構築し、
直接非リスト初期化
によって
il,
std::
forward
<
Args
>
(
args
)
...
から包含オブジェクトとして初期化する。
- このオーバーロードは、 std:: is_constructible_v < std:: decay_t < ValueType > , std:: initializer_list < U > & , Args... > と std:: is_copy_constructible_v < std:: decay_t < ValueType >> の両方が true である場合にのみ、オーバーロード解決に参加する。
目次 |
テンプレートパラメータ
| ValueType | - | 含まれる値の型 |
| 型要件 | ||
-
std::decay_t<ValueType>
は
CopyConstructible
の要件を満たさなければならない。
|
||
戻り値
新しい包含オブジェクトへの参照。
例外
T
のコンストラクタによってスローされる例外をスローします。例外がスローされた場合、以前に格納されていたオブジェクト(存在すれば)は破棄され、
*
this
は値を保持していない状態になります。
例
このコードを実行
#include <algorithm> #include <any> #include <iostream> #include <string> #include <vector> class Star { std::string name; int id; public: Star(std::string name, int id) : name{name}, id{id} { std::cout << "Star::Star(string, int)\n"; } void print() const { std::cout << "Star{\"" << name << "\" : " << id << "};\n"; } }; int main() { std::any celestial; // (1) emplace(Args&&... args); celestial.emplace<Star>("Procyon", 2943); const auto* star = std::any_cast<Star>(&celestial); star->print(); std::any av; // (2) emplace(std::initializer_list<U> il, Args&&... args); av.emplace<std::vector<char>>({'C', '+', '+', '1', '7'} /* no args */); std::cout << av.type().name() << '\n'; const auto* va = std::any_cast<std::vector<char>>(&av); std::for_each(va->cbegin(), va->cend(), [](char const& c) { std::cout << c; }); std::cout << '\n'; }
出力例:
Star::Star(string, int)
Star{"Procyon" : 2943};
St6vectorIcSaIcEE
C++17
関連項目
any
オブジェクトを構築する
(public member function) |
|
|
格納されたオブジェクトを破棄する
(public member function) |