TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 230 subscribers
Post #25654 17
Binding int from variant to reference in Foo.

Hello guys, my friend had a problem where he couldn't bind an int to int reference in Foo struct held in variant:

struct Foo {
int &abc;
};

std::variant<Foo, std::string> v;

// You can't!
v = Foo {
.abc = ...
}

So I developed a way to do that, it's pretty simple:

#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <variant>
#include <meta>
#include <ranges>

struct __attribute__((packed)) Foo {
int& abc;

~Foo() {
static_assert(sizeof(void*) == 8, "Use modern CPU.");

static_assert([]() consteval {
auto members = std::meta::nonstatic_data_members_of(
^^Foo,
std::meta::access_context::current()
);

for (auto member : members) {
auto type_info = std::meta::type_of(member);
std::size_t layout_size = std::meta::is_reference_type(type_info)
? sizeof(void*)
: std::meta::size_of(type_info);

if (layout_size != 8) {
return false;
}
}
return true;
}(), "All non-static data members of Foo must occupy 8 bytes in layout!");

if (reinterpret_cast<uintptr_t>(&abc) & 0x1) {
delete reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(&abc) &
~uintptr_t(0x1));
}
}
};

int main(void) {
std::variant<int, Foo> v;
v.emplace<0>(420);
v.emplace<1>(([&]() -> int& {
int* x = new int;
*x = std::get<0>(v);
x = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(x) | 0x1);
return *x;
})());
std::cout << *reinterpret_cast<int*>(
reinterpret_cast<uintptr_t>(&std::get<1>(v).abc) &
~uintptr_t(0x1))
<< std::endl;
return 0;
}

[https://godbolt.org/z/91rcbEdG5](https://godbolt.org/z/91rcbEdG5)

It's also memory safe.

Cheers.

https://redd.it/1v58tj3
@r_cpp
godbolt.org Compiler Explorer - C++ (x86-64 gcc 16.1) struct __attribute__((packed)) Foo { int& abc; ~Foo() { static_assert(sizeof(void*) == 8, "Use modern CPU."); static_assert([]() consteval { auto members = std::meta::nonstatic_data_members_of( ^^Foo,…
More from @r_cpp
  1. Sep 26, 2026Token Sequence Injection & Modern Macros: The Most Game-Changing Compile-Time Feature in C…
  2. Sep 25, 2026myStringStream.str("") Considered Harmful Under C++20 I was recently looking at some (rath…
  3. Sep 20, 2026A clever branch free optimization I'm the developer of memlz which is an extremely fast co…
  4. Sep 15, 2026Inside Boost.PolyCollection https://bannalia.blogspot.com/2026/09/inside-boostpolycollecti…
  5. Sep 11, 2026C++26: Standard Library Hardening Experiments https://www.cppstories.com/2026/hardening-ex…
  6. Sep 11, 2026MSVC C++23: constexpr cmath with LLVM Libc https://devblogs.microsoft.com/cppblog/msvc-c23…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →