Search code examples
c++c++17stdoptionalctaddeduction-guide

What is the point of `std::make_optional`


All the std::make_ are made redundant by C++17 with the introduction of Class template argument deduction (except make_unique and make_shared).

So what is the point of std::make_optional? As far as I can tell it does the exact same thing as the deduction guides for std::optional.

Is there a scenario where std::make_optional is preferred over deduction guides?


Solution

  • One example of the difference is when you want (for whatever reason) to make an optional containing an optional:

    #include <optional>
    #include <type_traits>
    
    int main()
    {
        auto inner=std::make_optional(325);
        auto opt2=std::make_optional(inner); // makes std::optional<std::optional<int>>
        auto opt3=std::optional(inner);      // just a copy of inner
        static_assert(std::is_same_v<decltype(opt2), std::optional<std::optional<int>>>);
        static_assert(std::is_same_v<decltype(opt3), std::optional<int>>);
    }