EnnFour
EnnFour

Reputation: 357

std::optional does not compile

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?

Upvotes: 1

Views: 1650

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58007

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.

Upvotes: 9

Related Questions