C++学习笔记 40 C++17 Optional
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 file
std::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 file
std::string result;
stream.close();
return result;
}
return {};
}
int testReadFileAsStringOptional() {
bool outSuccess;
std::string data = ReadFileAsString("data.txt", outSuccess);
//判断方式一,返回结果
if (data != "") {}
//判断方式二,外部值传递
if (outSuccess) {}
//判断方式三,Optional
std::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_value
if (data2) {
}
std::optional<int> count;
int c = count.value_or(100);
}
int main() {
testReadFileAsStringOptional();
std::cin.get();
}

浙公网安备 33010602011771号