简体   繁体   中英

C++17 — mapping types of member variables to std::optionals

How could I take some structure:

template<typename T>
typedef struct something_t {
  int x;
  int y;
  T z;
} something_t;

And create a utility type (possibly combined with some macros) which maps it to the same-shaped structure, but full of std::optionals instead. In other words, how would I write the partial struct in the following code,

template<typename T>
struct partial<T> { using type = ??? };

template<typename T>
using partial_something_t = partial<something_t<T>>::type;

...which would result in partial_something_t having this definition:

template<typename T>
typedef struct partial_something_t {
  std::optional<int> x;
  std::optional<int> y;
  std::optional<T> z;
} partial_something_t;

If you control the definition of something_t , you can change it this way:

template <template<typename> typename Wrapper, typename T>
struct new_something_t {
  Wrapper<int> x;
  Wrapper<int> y;
  Wrapper<T> z;
};

Then define a alias:

template <typename What> 
using Id = What;

Now your original something_t<T> becomes new_something_t<Id, T> and partial_something_t<T> is new_something_t<std::optional, T> .

One way to achieve this is to use local includes with macro overloading. Create a new.inl.h file that contains the inner structure some kind this way:

BEGIN_TEMPLATE_STRUCT(something_t)
  DECLARE_MEMBER(int, x)
  DECLARE_MEMBER(int, y)
  DECLARE_MEMBER(T, z)
END_TEMPLATE_STRUCT

Then create maybe two different header files (or only one as you prefer) that define the concrete macro definitions on their own, using push and pop_macro. Place the push_macros right before the include of this.inl.h file with the raw declaration of your struct, include the file and then don't forget to pop_macro to have a clean state afterwards. Header one then defines BEGIN_TEMPLATE_STRUCT as something_t and header two as partial_something_t and the sub-macros according to your wanted final types (DECLARE_MEMBER as std::optional...). The benefit of this approach is, that you have a minimal basic representation of your data that can be adapted to more complex ones. The major drawback is the (error-prone) macro-usage itself and some work to write at least more complex members like method types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM