Games101中的C++知识
std::optional(C++17)
框架代码:
1 2 3 4 5
| std::optional<hit_payload> trace( const Vector3f &orig, const Vector3f &dir, const std::vector<std::unique_ptr<Object> > &objects){...}
|
用途:
使 C++ 的函数返回多个值
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <iostream> #include <optional>
using namespace std;
struct Out { string out1 { "" }; string out2 { "" }; };
optional<Out> func(const string& in) { Out o; if (in.size() == 0) return nullopt; o.out1 = "hello"; o.out2 = "world"; return { o }; }
pair<bool, Out> func(const string& in) { Out o; if (in.size() == 0) return { false, o }; o.out1 = "hello"; o.out2 = "world"; return { true, o }; }
int main() { if (auto ret = func("hi"); ret.has_value()) { cout << ret->out1 << endl; cout << ret->out2 << endl; } return 0; }
|
创建 optional
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| optional<int> oEmpty; optional<float> oFloat = nullopt;
optional<int> oInt(10); optional oIntDeduced(10);
auto oDouble = std::make_optional(3.0); auto oComplex = make_optional<complex<double>>(3.0, 4.0);
optional<complex<double>> o7{in_place, 3.0, 4.0};
optional<vector<int>> oVec(in_place, {1, 2, 3});
auto oIntCopy = oInt;
|
访问 optional 对象
1 2 3 4 5 6 7 8 9 10
| cout << (*ret).out1 << endl; cout << ret->out1 << endl;
cout << ret.value().out1 << endl;
Out defaultVal; cout << ret.value_or(defaultVal).out1 << endl;
|