C++ Variant

梦想的初衷 提交于 2019-11-27 20:36:00

As of C++17, there’s std::variant.

If you can’t use that yet, you might want Boost.Variant. A similar, but distinct, type for modelling polymorphism is provided by std::any (and, pre-C++17, Boost.Any).

Just as an additional pointer, you can look for “type erasure”.

Fox

While Konrad's answer (using an existing standardized solution) is certainly preferable to writing your own bug-prone version, the boost variant has some overheads, especially in copy construction and memory.

A common customized approach is the following modified Factory Pattern:

  1. Create a Base interface for a generic object that also encapsulates the object type (either as an enum), or using 'typeid' (preferable).
  2. Now implement the interface using a template Derived class.
  3. Create a factory class with a templateized create function with signature:

template <typename _T> Base * Factory::create ();

This internally creates a Derived<_T> object on the heap, and retuns a dynamic cast pointer. Specialize this for each class you want implemented.

Finally, define a Variant wrapper that contains this Base * pointer and defines template get and set functions. Utility functions like getType(), isEmpty(), assignment and equality operators, etc can be appropriately implemented here.

Depending on the utility functions and the factory implementation, supported classes will need to support some basic functions like assignment or copy construction.

You can also go down to a more C-ish solution, which would have a void* the size of a double on your system, plus an enum for which type you're using. It's reasonably clean, but definitely a solution for someone who feels wholly comfortable with the raw bytes of the system.

C++17 now has std::variant which is exactly what you're looking for.

std::variant

Although the question had been answered for a long time, for the record I would like to mention that QVariant also does this.

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