Sep 6, 2018

[C++] std::optional use idiom [Sum type]

using T = /* some object type */;

struct S {
  optional<T> maybe_T;    

  void construct_the_T(int arg) {
    // We need not guard against repeat initialization;
    // optional's emplace member will destroy any 
    // contained object and make a fresh one.        
    maybe_T.emplace(arg);
  }

  T& get_the_T() { 
    assert(maybe_T);
    return *maybe_T;    
    // Or, if we prefer an exception when maybe_T is not initialized:
    // return maybe_T.value();
  }

  // ... No error-prone handwritten special member functions! ...
};


Reference:
https://vsdmars.blogspot.com/2018/05/caccu2018-tricks-library-implementation.html
https://vsdmars.blogspot.com/2018/06/c-regular-type.html

golang:
https://godoc.org/google.golang.org/cloud/internal/optional
src:
https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/internal/optional/optional.go

Java:
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.