GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::make_optional - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. optional
  3. make_optional

最終更新日時: 2026年09月11日 13時06分31秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<optional>

std::make_optional(C++17)

namespace std {
  template <class T>
  constexpr optional<see below> make_optional(T&& v);    // (1)

  template <class T, class... Args>
  constexpr optional<T> make_optional(Args&&... args);   // (2)

  template <class T, class U, class... Args>
  constexpr optional<T> make_optional(
                            std::initializer_list<U> il,
                            Args&&... args);             // (3)
}

概要

有効な値を保持するoptionalオブジェクトを構築する。

  • (1) : 型Tの値を受け取り、それを有効値として保持するoptionalオブジェクトを構築する
  • (2) : 型Tのコンストラクタ引数を受け取り、関数内でTオブジェクトを構築し、それを有効値として保持するoptionalオブジェクトを構築する
  • (3) : 型Tのコンストラクタ引数として初期化子リストと任意個の引数を受け取り、関数内でTオブジェクトを構築し、それを有効値として保持するoptionalオブジェクトを構築する

効果

  • (1) : return optional<decay_t<T>>(std::forward<T>(v)); と等価の処理を行う
  • (2) : return optional<T>(in_place, std::forward<Args>(args)...); と等価の処理を行う
  • (3) return optional<T>(in_place, il, std::forward<Args>(args)...); と等価の処理を行う

例

#include <cassert>
#include <optional>
#include <type_traits>
#include <string>
#include <vector>

int main()
{
  // (1)
  {
    auto p = std::make_optional("Hello");
    static_assert(std::is_same_v<decltype(p), std::optional<const char*>>);
  }

  // (2)
  {
    auto p = std::make_optional<std::string>(3, 'A');

    assert(p.value() == "AAA");
    static_assert(std::is_same_v<decltype(p), std::optional<std::string>>);
  }

  // (3)
  {
    std::allocator<int> alloc;
    auto p = std::make_optional<std::vector<int>>({3, 1, 4}, alloc);

    assert(p.value()[0] == 3);
    assert(p.value()[1] == 1);
    assert(p.value()[2] == 4);
    static_assert(std::is_same_v<decltype(p), std::optional<std::vector<int>>>);
  }
}

出力

バージョン

言語

  • C++17

処理系

  • Clang: 4.0.1 ✅
  • GCC: 7.2 ✅
  • Visual C++: ??

参照

  • LWG Issue 3627. Inconsistent specifications for std::make_optional overloads
    • C++26で、(1)の仕様が「戻り値(Returns)」から他のオーバーロードと同じ「効果(Effects): 〜と等価」の形式へ変更された(意味は変わらない編集上の整合化)
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.