Search code examples
c++c++11typestemplate-meta-programmingtype-traits

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


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?


Solution

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