0

I'm first trying to understand optional in c++ (supported in g++ version 17) But I had some error which seems pretty easy but I can't understand....

Here's easy example.

#include <iostream>
#include <optional>
#include <string>
#include <vector>
using namespace std;

struct Animal {
    std::string name;

};

struct Person {
    std::string name;
    std::vector<Animal> pets;

    std::optional<Animal> pet_with_name(const std::string &name) {
        for (const Animal &pet : pets) {
            if (pet.name == name) {
                return pet;
            }
        }
        return std::nullopt;
    }
};

int main() {
    Person john;
    john.name = "John";

    Animal fluffy;
    fluffy.name = "Fluffy";
    john.pets.push_back(fluffy);

    Animal furball;
    furball.name = "Furball";
    john.pets.push_back(furball);

    std::optional<Animal> whiskers = john.pet_with_name("Whiskers");
    if (whiskers) {
        std::cout << "John has a pet named Whiskers." << std::endl;
    }
    else {
        std::cout << "Whiskers must not belong to John." << std::endl;
    }
}

Such an easy code and I can understand it. But I got some errors.

test.cpp:15:10: error: ‘optional’ in namespace ‘std’ does not name a template type
     std::optional<Animal> pet_with_name(const std::string &name) {
          ^~~~~~~~

I'm running through Ubuntu 18.04 lts in windows 10 And it doesn't return error at

#include <optional>

and its g++ version is g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

marks jun
  • 25
  • 4

1 Answers1

0

Your need a latest compiler and compile the above code using C++17 flag as shown below.

g++ -std=c++1z main.c 

Here main.c is the file containing your code.

D.Malim
  • 86
  • 6