Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 424cbbeb authored by Jakub Tyszkowski's avatar Jakub Tyszkowski
Browse files

common/strings: Support classes with operator<<(std::ostream&, const T&)

This allows to reuse all the existing string conversion logic for custom
classes for which we already have these defined:
  std::ostream& operator<<(std::ostream& os, const T& obj)

Bug: 150670922
Tag: #feature
Test: atest packages/modules/Bluetooth/system/gd/common/strings_test.cc
Sponsor: jpawlowski@
Change-Id: Ie31584231800573b5dbc59caba1cccc0c0787be2
parent 099bd1e4
Loading
Loading
Loading
Loading
+7 −0
Original line number Diff line number Diff line
@@ -36,6 +36,13 @@
namespace bluetooth {
namespace common {

template <typename T>
inline std::string ToString(const T& value) {
  std::stringstream tmp;
  tmp << value;
  return tmp.str();
}

// Convert number into a hex string prefixed with 0x
template <typename T>
std::string ToHexString(T x) {
+11 −0
Original line number Diff line number Diff line
@@ -256,4 +256,15 @@ TEST(StringsTest, string_format_time_with_ms_test) {
  ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point2, gmtime), StrEq("2009-02-13 23:31:30.001"));
}

class ExampleClass {};
std::ostream& operator<<(std::ostream& os, const ExampleClass& obj) {
  os << "ExampleClass";
  return os;
}

TEST(StringsTest, example_class_to_string_test) {
  ExampleClass obj;
  ASSERT_THAT(ToString(obj), StrEq("ExampleClass"));
}

}  // namespace testing