// 取值前进行判断,隐式 bool 运算转换 auto nameOpt = getName(false); if (nameOpt) { std::cout << "test_value 2. name: " << nameOpt.value() << '\n'; } else { std::cout << "test_value 2. value not set\n"; }
nameOpt = getName(true); if (nameOpt) { std::cout << "test_value 3. name: " << nameOpt.value() << '\n'; } else { std::cout << "test_value 3. value not set\n"; }
// 取值前进行判断,has_value 进行判断 nameOpt = getName(false); if (nameOpt.has_value()) { std::cout << "test_value 4. name: " << nameOpt.value() << '\n'; } else { std::cout << "test_value 4. value not set\n"; }
nameOpt = getName(true); if (nameOpt.has_value()) { std::cout << "test_value 5. name: " << nameOpt.value() << '\n'; } else { std::cout << "test_value 5. value not set\n"; } }
// value_or 如果检测到未设置值,则会返回一个默认值 voidtest_value_or() { auto name = getName(false).value_or("none"); std::cout << "test_value_or 0. name: " << name << '\n';
name = getName(true).value_or("none"); std::cout << "test_value_or 1. name: " << name << '\n'; }
intmain() { test_value(); test_value_or(); }
程序输出:
name is empty test_value 0. throw: Bad optional access test_value 1. name: Tom test_value 2. value not set test_value 3. name: Tom test_value 4. value not set test_value 5. name: Tom test_value_or 0. name: none test_value_or 1. name: Tom