farm-ng-core
enum.h
Go to the documentation of this file.
1 // Copyright 2022, farm-ng inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // FARM_ENUM is a fork of MY_ENUM.
16 //
17 // https://github.com/facebookincubator/MY_ENUM/
18 //
19 // Copyright (c) Facebook, Inc. and its affiliates.
20 //
21 // This source code is licensed under the MIT license found in the
22 // LICENSE file in the root directory of this source tree.
23 
24 #pragma once
25 
27 
28 #include <istream>
29 #include <ostream>
30 
31 #define FARM_ENUM_IOSTREAM_OVERLOAD(EnumName) \
32  namespace enum_wrapper_ { \
33  inline auto operator<<(std::ostream &os, EnumName##Impl value) \
34  -> std::ostream & { \
35  os << toPretty(value); \
36  return os; \
37  } \
38  inline auto operator>>(std::istream &is, EnumName##Impl &value) \
39  -> std::istream & { \
40  std::string str; \
41  is >> str; \
42  if (!trySetFromString(value, str)) { \
43  throw std::runtime_error(std::string("Bad Value: ") + str); \
44  } \
45  return is; \
46  } \
47  } // namespace enum_wrapper_
48 
49 // Convenience marco which defines the enum plus alias and adds the ostream
50 // overload.
51 #define FARM_ENUM(EnumName, ...) \
52  FARM_ENUM_WITHOUT_IOSTREAM(EnumName, __VA_ARGS__); \
53  FARM_ENUM_IOSTREAM_OVERLOAD(EnumName)
54 
55 // Convenience marco which defines the enum and adds the ostream overload.
56 #define FARM_ENUM_DEF(EnumName, ...) \
57  FARM_ENUM_WITHOUT_IOSTREAM_DEF(EnumName, __VA_ARGS__); \
58  FARM_ENUM_IOSTREAM_OVERLOAD(EnumName)
enum_without_iostream.h