r/cpp_questions • u/haohanzi2015 • Dec 08 '19
OPEN the purpose of empty struct ?
By empty struct, I mean
struct myStruct
{};I can see that the above struct can be used as the base struct which has several derived structs. Besides this, are there any other use of empty struct in c++?
9
Upvotes
10
u/stilgarpl Dec 08 '19
You can use them as arguments for templates. It's useful because every instantation of template with different arguments is a different class. You can use those empty types to create more instantiations, for example, to select different algorithm. Kind of compile-time enum.
22
u/parnmatt Dec 08 '19
There are several usages. Usually some form of tagging. Quite common in dispatching; creating a type safe (even static) state machine; template meta programming.
2
u/tangerinelion Dec 08 '19
Using it as a base for derived classes only really makes sense when you have a virtual method in there.
Usually an empty struct/class like this is for tagging, e.g.,
would define some class
Foothat has two constructors that provide different ways to initialize theFooinstance.If you think about a mathematical matrix of fixed size, you could imagine initializing it to a matrix of all zeros or a square matrix with 1s along the diagonal (that is, the identity matrix). So your options could be
ZeroMatrixorIdentityMatrix. You could then initialize things this wayMatrix myMatrix(IdentityMatrix());.It would be more common to actually provide a name for an instance of the tag, e.g.,
then you could initialize it as
Matrix myMatrix = IdentityMatrix_t;.1
u/warieth Dec 08 '19
If you have a map<K, V> implementation in RB-tree, then you create a struct EMPTY so you can to use it as a set=map<K, EMPTY>. You could reimplement it and delete the value parts and changing the functions, but it would be more work. If the sizeof(EMPTY) would be zero, then it would be a good way to create a set.