Advantages of an empty class in C++

后端 未结 9 1552
夕颜
夕颜 2020-12-08 20:51

What could be the possible advantages/uses of having an empty class?

P.S: This question might sound trivial to some of you but it is just for learning purpose and h

相关标签:
9条回答
  • 2020-12-08 21:51

    The answer by MartinStettner is fine though just to highlight an important point here: The concept of iterator tags or for that matter any tags in C++, is not strictly dependent on empty classes. The C++ tags, if stl writers would have wanted to, could well have been non-empty classes; that should work but then it won't add any additional value; at least for compile time acrobatics that it is usually reserved for.

    0 讨论(0)
  • 2020-12-08 21:52

    Here is an interesting link with answers to why its allowed. You might find this helpful to find situations where it might be useful.

    0 讨论(0)
  • 2020-12-08 21:53

    An empty class could be used as a "token" defining something unique; in certain patterns, you want an implementation-agnostic representation of a unique instance, which has no value to the developer other than its uniqueness. One example is Unit of Work; you may not care one bit about what's going on inside your performer, but you want to tell that performer that the tasks you're telling it to perform are part of an atomic set. An empty class representing the Unit of Work to the outside world may be perfect in this case; almost anything a Unit of Work object could store or do (encapsulating a DB transaction, exposing Commit/Rollback behaviors) would start tying you to a particular implementation, but an object reference is useful to provide a unique but copyable and passable reference to the atomic set of tasks.

    0 讨论(0)
提交回复
热议问题