NullableOStream.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
  17. #define FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
  18. #include <iostream>
  19. namespace android {
  20. namespace lshal {
  21. template<typename S>
  22. class NullableOStream {
  23. public:
  24. explicit NullableOStream(S &os) : mOs(&os) {}
  25. explicit NullableOStream(S *os) : mOs(os) {}
  26. NullableOStream &operator=(S &os) {
  27. mOs = &os;
  28. return *this;
  29. }
  30. NullableOStream &operator=(S *os) {
  31. mOs = os;
  32. return *this;
  33. }
  34. template<typename Other>
  35. NullableOStream &operator=(const NullableOStream<Other> &other) {
  36. mOs = other.mOs;
  37. return *this;
  38. }
  39. const NullableOStream &operator<<(std::ostream& (*pf)(std::ostream&)) const {
  40. if (mOs) {
  41. (*mOs) << pf;
  42. }
  43. return *this;
  44. }
  45. template<typename T>
  46. const NullableOStream &operator<<(const T &rhs) const {
  47. if (mOs) {
  48. (*mOs) << rhs;
  49. }
  50. return *this;
  51. }
  52. S& buf() const {
  53. return *mOs;
  54. }
  55. operator bool() const { // NOLINT(google-explicit-constructor)
  56. return mOs != nullptr;
  57. }
  58. private:
  59. template<typename>
  60. friend class NullableOStream;
  61. S *mOs = nullptr;
  62. };
  63. } // namespace lshal
  64. } // namespace android
  65. #endif // FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_