Сначала я пытаюсь понять необязательное в c ++ (поддерживается в g ++ версии 17). Но у меня была ошибка, которая кажется довольно простой, но я не понимаю ....
Вот простой пример.
#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;
}
}
Такой простой код, и я могу его понять. Но я получил ошибок .
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) {
^~~~~~~~
Я бегу через Ubuntu 18.04 lts в windows 10 И он не возвращает ошибку при
#include <optional>
и его версия g ++ - g ++ (Ubuntu 7.5.0-3ubuntu1 ~ 18.04) 7.5.0