How to use optional

Question:
How can I use optional on Replit? It doesn’t seem to work (no template named ‘optional’)

#include <iostream>

using namespace std;

class Lexer {
  public:
    optional<char> currentCharacter;
}
2 Likes

Shouldn’t you include #include <optional> too?

3 Likes

Oh, guess I forgot that. I’m still getting the same error tho

2 Likes

I did a bit of research, and I think I found a solution. I’m not sure what C++ version Replit uses or how to check, but <optional> is only available in the C++ 17 standard. You will need to include <experimental/optional> instead.

Here is the refactored code:

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

using namespace std;

class Lexer {
  public:
    experimental::optional<char> currentCharacter;
};

You could probably also use using namespace experimental; (which would need to come after using namespace std;), but I would not recommend it because using more than one namespace is considered bad practice.


Edit: It turns out you can actually check C++'s version, within the code, by doing something of the sort:

#include <iostream>

using namespace std;

int main() {
  cout << __cplusplus << endl;
}

This outputted 201402, which is C++ 14. Sorry this is a bit off-topic, but this explains why it wasn’t working.

3 Likes

or to update C++:

sed -i '/override CFLAGS/s/$/ -std=c++2b/' Makefile

then you can #import <optional>

2 Likes
sed: -e expression #1, char 21: unknown option to `s'

oops. The edited command should work

1 Like

I’m still getting the same error (no template named ‘optional’)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.