bison_wrap.h 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_SYNTAX_BISON_WRAP_H_
  5. #define EXECUTABLE_SEMANTICS_SYNTAX_BISON_WRAP_H_
  6. #include <optional>
  7. #include "common/check.h"
  8. namespace Carbon {
  9. // Bison requires that types be default initializable for use with its variant
  10. // semantics. This wraps arbitrary types to support a default constructor, while
  11. // still requiring they be properly initialized.
  12. template <typename T>
  13. class BisonWrap {
  14. public:
  15. // Assigning a value initializes the wrapper.
  16. BisonWrap& operator=(T&& rhs) {
  17. val = std::move(rhs);
  18. return *this;
  19. }
  20. // Support transparent conversion to the wrapped type, erroring if not
  21. // initialized.
  22. operator T() {
  23. CHECK(val.has_value());
  24. T ret = std::move(*val);
  25. val.reset();
  26. return ret;
  27. }
  28. private:
  29. std::optional<T> val;
  30. };
  31. } // namespace Carbon
  32. #endif // EXECUTABLE_SEMANTICS_SYNTAX_BISON_WRAP_H_