std::optional causing advanced patterns when used with derived classes in C++20
I'm optimizing some code but I'm performance testing and I'm working with an scenario when trying to use `std::optional` with a derived class in C++20... I have a base class and a derived class, and I want to return an `std::optional` of the base class type from a factory function that creates instances of the derived class. However, when I try to use the optional, it doesn't seem to correctly hold the derived class instance, leading to unexpected behavior. Here's a simplified version of my code: ```cpp #include <iostream> #include <optional> #include <memory> class Base { public: virtual void display() const { std::cout << "Base class" << std::endl; } virtual ~Base() = default; }; class Derived : public Base { public: void display() const override { std::cout << "Derived class" << std::endl; } }; std::optional<std::unique_ptr<Base>> createInstance(bool createDerived) { if (createDerived) { return std::make_unique<Derived>(); } return std::nullopt; } int main() { auto instance = createInstance(true); if (instance) { (*instance)->display(); } else { std::cout << "No instance created" << std::endl; } return 0; } ``` When I run this code, I get a compilation behavior saying that `std::unique_ptr<Base>` want to be implicitly converted to `std::optional<std::unique_ptr<Base>>`. I've tried wrapping the `std::make_unique<Derived>()` call with `std::optional` directly, but that didn't help either. I've considered using `std::shared_ptr` instead, but I would prefer to stick with `std::unique_ptr` for performance reasons. Could anyone point out what I'm doing wrong here or suggest a way to correctly use `std::optional` with `std::unique_ptr` in this context? My development environment is macOS. Any help would be greatly appreciated! For context: I'm using C++ on Linux. I'd really appreciate any guidance on this. Could this be a known issue? I'm coming from a different tech stack and learning C++.