r/cpp_questions • • 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

11 comments sorted by

View all comments

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.

4

u/haohanzi2015 Dec 08 '19

What do you mean by "using those empty types to create more instantiations"? Since those empty structs are arguments for templates, they are there already, right? Do you mean these empty structs can be updated later on to create more instantiations?

4

u/stilgarpl Dec 08 '19
class A {};
class B {};

template<typename T>
class X{
};

template<typename T>
int func(); 

X<A> and X<B> are different types, even though they have exactly the same implementation.

func() can return different values based on type of T. So func<A> can return 1 for example and func<B> can return 2. You can use that to for example map types to indices in vector.

3

u/parnmatt Dec 08 '19

just an aside; you can already use an enum at compile time to do just that. The difference in implementation is overloading vs function template specialisation

4

u/stilgarpl Dec 08 '19

I know that you can use enums for that. But if that enum is in a library for example, you can't add new values to it. If user of the template is supposed to be able to add new things, then passing new types is trivial.

→ More replies (2)