Skip to content

Latest commit

 

History

History
111 lines (82 loc) · 2.31 KB

195.md

File metadata and controls

111 lines (82 loc) · 2.31 KB
Info

Example

struct empty {};
struct ebco : empty {}; // Empty Base Class Optimization (EBCO)

static_assert(sizeof(empty) == 1);
static_assert(sizeof(ebco) == 1);

struct no_unique_address {
  [[no_unique_address]] struct {} empty;
};

static_assert(sizeof(no_unique_address) == 1);

https://godbolt.org/z/P9KK84

Puzzle

  • Can you add an optional field of type T to foo only when Enable == true?

    • Preferably by leveraging [[no_unique_address]] attribute
template<auto Enable, class T = void>
struct [[gnu::packed]] foo {
  int i{};
  bool b{};
  /*TODO - optional field of type T when Enabled */
};

static_assert(sizeof(int) + sizeof(bool) == sizeof(foo<false>));
static_assert(sizeof(int) + sizeof(bool) + sizeof(int) == sizeof(foo<true, int>));

struct bar{};
static_assert(sizeof(int) + sizeof(bool) == sizeof(foo<true, bar>));

struct baz{ int i{}; };
static_assert(sizeof(int) + sizeof(bool)  + sizeof(baz) == sizeof(foo<true, baz>));

https://godbolt.org/z/sj5bEx

Solutions

namespace detail {
struct disabled{};

template <auto Enable, class T>
  using when_enabled_t = std::conditional_t<Enable, T, disabled>;
}

template<auto Enable, class T = void>
struct [[gnu::packed]] foo {
  int i{};
  bool b{};
  [[no_unique_address]] detail::when_enabled_t<Enable, T> t{};
};

https://godbolt.org/z/ov5d6z

template<auto Enable, class T = void>
struct [[gnu::packed]] foo {
  int i{};
  bool b{};
  struct empty{};
  [[no_unique_address]] std::conditional_t<Enable, T, empty> c;
};

https://godbolt.org/z/9rGrTj

template<auto Enable, class T = void>
struct [[gnu::packed]] foo {
  int i{};
  bool b{};
};

template<class T>
struct [[gnu::packed]] foo<true,T> {
    int i{};
    bool b{};
    [[no_unique_address]] T t{};
};

https://godbolt.org/z/oor65K

template<auto Enable, class T = void>
struct [[gnu::packed]] foo {
  int i{};
  bool b{};
  [[no_unique_address]] std::conditional_t<Enable, T, std::tuple<>> t{};
};

https://godbolt.org/z/fne13q