PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to distinguish empty struct from one char?

 October 28, 2022     c++, is-empty, struct     No comments   

Issue

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.



Answered By - gsamaras
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing