if (!fin) { fin.close(); return {}; // same as return nullopt; }
// todo: read file fin.close(); return"gjgjh"; }
intmain(){ optional<string> str = readFileAsString("data.txt"); cout << str.value_or("empty") << endl; // use default value here
// if str has value or not if (str) { // same as if(str.has_value()) cout << "file read successfully\n"; cout << *str << '\n'; cout << str.value() << endl; } else { cout << "file cannot be opened\n"; }
intmain(){ variant<int, string> v, w; v = 12; int i = get<int>(v); w = get<int>(v); w = get<0>(v); // index 0: int, index 1: string w = v; // same effect as the previous line
// get<double>(v); // error: no double in [int, string] // std::get<3>(v); // error: valid index values are 0 and 1
intmain(){ pair<int, string> studentInfo{1, "gjh"}; // also can be tuple or struct auto[id, name]=studentInfo; // or const auto& [id, name]=studentInfo; cout << "id: " << id << ", name: " << name << endl;