/Users/deen/code/yugabyte-db/src/yb/util/strongly_typed_string.h
Line | Count | Source |
1 | | // Copyright (c) YugaByte, Inc. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
4 | | // in compliance with the License. You may obtain a copy of the License at |
5 | | // |
6 | | // http://www.apache.org/licenses/LICENSE-2.0 |
7 | | // |
8 | | // Unless required by applicable law or agreed to in writing, software distributed under the License |
9 | | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
10 | | // or implied. See the License for the specific language governing permissions and limitations |
11 | | // under the License. |
12 | | // |
13 | | |
14 | | #ifndef YB_UTIL_STRONGLY_TYPED_STRING_H |
15 | | #define YB_UTIL_STRONGLY_TYPED_STRING_H |
16 | | |
17 | | #include <string> |
18 | | |
19 | | #include <boost/preprocessor/cat.hpp> |
20 | | |
21 | | // A "strongly-typed string" tool. This is needed to prevent passing the wrong string as a |
22 | | // function parameter. Conversion from strongly-typed strings to std::string is automatic, but the |
23 | | // reverse conversion is always explicit. |
24 | | #define YB_STRONGLY_TYPED_STRING(TypeName) \ |
25 | | class BOOST_PP_CAT(TypeName, _Tag); \ |
26 | | typedef ::yb::StronglyTypedString<BOOST_PP_CAT(TypeName, _Tag)> TypeName; |
27 | | |
28 | | namespace yb { |
29 | | |
30 | | template <class Tag> |
31 | | class StronglyTypedString { |
32 | | public: |
33 | | // This is public so that we can construct a strongly-typed string value out of a regular one if |
34 | | // needed. In that case we'll have to spell out the class name, which will enforce readability. |
35 | 96.7k | explicit StronglyTypedString(const std::string& value) : value_(value) {} |
36 | | |
37 | | bool operator==(const StronglyTypedString<Tag>& other) const { |
38 | | return value_ == other.value_; |
39 | | } |
40 | | |
41 | | bool operator!=(const StronglyTypedString<Tag>& other) const { |
42 | | return !(*this == other); |
43 | | } |
44 | | |
45 | 819k | const std::string& ToString() const { return value_; } |
46 | | |
47 | | private: |
48 | | std::string value_; |
49 | | }; |
50 | | |
51 | | } // namespace yb |
52 | | |
53 | | #endif // YB_UTIL_STRONGLY_TYPED_STRING_H |