3

Kind of a silly question, but I'm curious and I haven't found this explained. Is it legal to construct a std::optional<std::nullopt_t>? If you did, what would

std::optional<std::nullopt_t> x(std::nullopt);

do? Would x contain a value or not?

Joshua Green
  • 1,517
  • 1
  • 10
  • 14
  • 11
    [It's not allowed](https://en.cppreference.com/w/cpp/utility/optional): _"In addition, a program is ill-formed if it instantiates an optional with the (possibly cv-qualified) tag types `std::nullopt_t` or `std::in_place_t`."_ – Miles Budnek Jul 15 '23 at 02:01
  • [live link to gcc error](https://wandbox.org/permlink/E3Kb8KmDEJdCp7Q7) – Ryan Haining Jul 15 '23 at 02:38
  • *Is it legal to construct...* Human sacrifice! Dogs and cats living together! Mass hysteria! – Eljay Jul 15 '23 at 16:45

1 Answers1

6

As pointed out in the comments, instantiating a optional with nullopt_t (or in_place_t) is explicitly forbidden and will fail with a compile error.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982