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

Time:12-01

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?

CodePudding user response:

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);

CodePudding user response:

#include <type_traits>

struct A { };
struct B : A { };
struct C : B { 
  [[no_unique_address]] A a;
};

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

Demo.

  • Related