template <class... Args>
constexpr std::optional<reference> try_emplace_back(Args&&... args); // (1) C++26
概要
末尾へ直接構築を試みる。容量超過時は例外を送出せず、std::nulloptを返す。
効果
size() < Nの場合、std::forward<Args>(args)...から構築した要素を末尾に追加する。そうでない場合、何もしない。
戻り値
要素が追加された場合は追加された要素への参照を保持したstd::optional、追加できなかった場合はstd::nulloptを返す。
例外
投げない(Tのコンストラクタが例外を送出する場合を除く)
計算量
定数時間
例
#include <print>
#include <inplace_vector>
#include <string>
int main()
{
std::inplace_vector<std::string, 2> iv;
auto r1 = iv.try_emplace_back("hello");
auto r2 = iv.try_emplace_back("world");
auto r3 = iv.try_emplace_back("overflow");
std::println("{}", (r1 ? *r1 : "(nullopt)"));
std::println("{}", (r2 ? *r2 : "(nullopt)"));
std::println("{}", (r3 ? "(success)" : "(failed)"));
}
出力
hello
world
(failed)
バージョン
言語
- C++26
処理系
- Clang: 23 ✅
- GCC: 16 ✅
- Visual C++: 2026 Update 2 ❌