跳到主要內容

發表文章

目前顯示的是 1月, 2020的文章

std::optional 的未來?

std::optional<T&> 的未來? 前言 春節就是拋拋走,趁著搭車的時間看完 JeanHeyd Meneide (ThePhantomDerpstorm/ThePhD) 的 血淚控訴 To Bind and Loose a Reference 1 ,他聲稱:標準委員會因為一個不存在的對手,訂定了一個殘缺的 std::optional 。文章非常值得一讀,寫不出配得上的心得,只好寫一篇筆記。 Nullable 型別 C++17 增添了 std::optional<T> ,C++20 加入了 std::variant<Ts...> ,C++2x 預計會出現 std::expected<T> ,這些工具的相同點在於他們都是 nullable 型別 ─ 物件狀態可以是含有 T 或者不含有 T (也就是 null),雖然應用在不同的情境上,但某種程度上都可以理解為特化版的指標。 Reference 有甚麼問題? std::optional 在 cppreference.com 裡的描述 2 裡面有一句話: There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. 同樣適用於 std::variant 、 std::expected 。其實在 Boost.Optional 或是 Boost.Variant 都是支援 reference 型別的,然而 C++ 標準委員會對下面這段程式分裂成兩派不同的見解 (範例取自 JeanHeyd Meneide): # include <optional> # include <iostream> int main ( int , char * [ ] ) { int x = 5 ; int y = 24 ; std :: optional < int & > opt = x ; opt = y ; std :: cout <