Search code examples
c++structis-empty

How to distinguish empty struct from one char?


I'm trying to implement own functor and faced with empty capture lambdas. How to distinguish empty struct from one char? Is there are any "real" size at compile time? I want just ignore empty lambdas to prevent useless allocations.

struct EmptyStruct {};
struct CharStruct { char c; };


int main()
{
    char buffer1[sizeof(EmptyStruct)]; // size 1 byte
    char buffer2[sizeof(CharStruct)]; // size 1 byte
}

Solution

  • You cannot do that with sizeof(), use std::is_empty, like this:

    #include <iostream>
    #include <type_traits>
    
    struct EmptyStruct {};
    struct CharStruct { char c; };
    int main(void)
    {
      std::cout << std::boolalpha;
      std::cout << "EmptyStruct " << std::is_empty<EmptyStruct>::value << '\n';
      std::cout << "CharStruct " << std::is_empty<CharStruct>::value << '\n';
      return 0;
    }
    

    Output:

    EmptyStruct true
    CharStruct false
    

    as @RichardCritten commented.