Best way to encapsulate “optional” fields within a struct generically in C++?

允我心安 提交于 2019-12-05 10:21:23

Sounds like you want boost.optional.

Keep it simple. Use a flag member variable that you can set by or-ing constants together and inspect by and-ing them.

Problem with sentinel values is choosing ones that are not also legal field values (now and in the future).

Both string and vector has an empty default state, which you can test for with if (username.empty()) etc.

For a subaccountid I would guess that 0 would be a similar empty value. Otherwise -1 could be ok.

I'd use one a flag. I can propose you two method, one keeping the value on the heap and one on the stack.

In the first you use a std::pair and the first field is the existence-flag. The second approach is via a boost::shard_ptr, if pointer points to 0 the field is not existing.

In both the cases my advice is not to access directly to the element in Value but using instead a couple of functions. const Value& value() const { return } Value& value() { return }

francesco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!