2

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
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
kerrytazi
  • 583
  • 1
  • 4
  • 15
  • "*I want just ignore empty lambdas to prevent useless allocations.*" FYI: You cannot *ignore* empty lambdas. Lambdas (until C++20) are not default constructible, so you cannot just create them when you need to call them. You have to "store" them somewhere. Now, you can inherit from an empty lambda and thus get empty base optimization (but again, you need to construct the lambda from an existing object). But that's about the best you can do. – Nicol Bolas Apr 13 '19 at 15:39

1 Answers1

7

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305