1

This code does not compile with the command g++ -std=c++17 main.cpp

#include <iostream>
#include <experimental/optional>

int main()
{
    std::optional<int> x;
    std::cout << "Hello World";
    return 0;
}

The Errors are the following:

  1. error: ‘optional’ is not a member of ‘std’
  2. error: expected primary-expression before ‘int’

Is there a way to get this code to compile?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
EnnFour
  • 323
  • 2
  • 8

1 Answers1

9

The <experimental/optional> header doesn't define std::optional but rather std::experimental::optional. To get std::optional, which is a (non-experimental) part of the C++17 standard, you should just #include <optional>.

Try on godbolt.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82