Optional
Optional: 三种处理可能存在,可能不存在的数据的方式之一
#include<iostream>
#include<string>
#include<fstream>
#include<optional>std::string ReadFileAsString(const std::string& filePath, bool& outSuccess) {std::ifstream stream(filePath);if (stream) {//read filestd::string result;stream.close();return result;}return std::string();
}std::optional<std::string> ReadFileAsStringOptional(const std::string& filePath) {std::ifstream stream(filePath);if (stream) {//read filestd::string result;stream.close();return result;}return {};
}int testReadFileAsStringOptional() {bool outSuccess;std::string data = ReadFileAsString("data.txt", outSuccess);//判断方式一,返回结果if (data != "") {}//判断方式二,外部值传递if (outSuccess) {}//判断方式三,Optionalstd::optional<std::string> data2 = ReadFileAsStringOptional("data.txt");if (data2.has_value()) {std::cout << "File read successfully. data: " << data2.value() << "\n";std::cout << "File read successfully. data: " << data2.value_or("hello world") << "\n";} else {std::cout << "File couldn't be opened.\n";}//因为data2对象有一个bool运算符,所以不用谢has_valueif (data2) {}std::optional<int> count;int c = count.value_or(100);
}int main() {testReadFileAsStringOptional();std::cin.get();
}