Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is empty struct defined by C++ standard?

Tags:

Is there any std::empty struct or something similar or do I need to define my own:

struct empty{}; 

This can be used very nice in combination with std::conditional or other new std features and I wonder if the standard defines it or not.

like image 962
Mircea Ispas Avatar asked May 21 '13 09:05

Mircea Ispas


People also ask

Can we define empty structure in C?

Empty struct in C is undefined behaviour (refer C17 spec, section 6.7. 2.1 ): If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.

Can you define empty struct?

An empty structIt occupies zero bytes of storage.

How is struct defined in C?

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

What is size of empty struct in C?

Sizeof empty struct is 0 byte in C but in C++ it is 1 byte.


1 Answers

There is a section to add this kind of construct as part of the Variant proposal (n4542).

After being voted on,

What do we want to call the “empty_t” stand-in type?
empty_t 4
empty 4
one_t 1
blank 6
blank_t 7
monostate 7

Runoff:
blank* 3
monostate 8

the agreed upon name would be: std::monostate.


It would be defined the following way:

// 2.?, Explicitly default-constructed alternative struct monostate {}; bool operator<(const monostate&, const monostate&) constexpr { return false; } bool operator>(const monostate&, const monostate&) constexpr { return false; } bool operator<=(const monostate&, const monostate&) constexpr { return true; } bool operator>=(const monostate&, const monostate&) constexpr { return true; } bool operator==(const monostate&, const monostate&) constexpr { return true; } bool operator!=(const monostate&, const monostate&) constexpr { return false; } 
like image 66
Trevor Hickey Avatar answered Oct 07 '22 13:10

Trevor Hickey