How to make a type T that `std::is_empty_v<T> && sizeof(T) > 1` is true?

Viewed 110

I came across an interesting quiz question at here:

Write a translation unit containing a class type T, such that std::is_empty_v<T> is true, and yet sizeof(T) is greater than 1.

I'v thought about it for some time, but no solution.

How to make a type T that std::is_empty_v<T> && sizeof(T) > 1 is true?

2 Answers

std::is_empty checks if there are no members. You can use alignment to force a size greater than 1:

struct alignas(2) T {};

static_assert(std::is_empty_v<T>);
static_assert(sizeof(T) > 1);

Since two identical empty classes cannot share the same address, we can create a class that inherits an empty base and also has an empty base as a member to prohibit EBO and make its size greater than 1.

#include<type_traits>

struct B { };
struct D : B { [[no_unique_address]] B b; };

static_assert(std::is_empty_v<D> && sizeof(D) > 1);

Demo.

Related