Storage Type Narrowing

Run Settings
LanguageC++
Language Version
Run Command
#include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> template<size_t N> struct Storage { uint8_t storage[N]; }; template<typename T> inline Storage<sizeof(T)> storage_convert(T value) { Storage<sizeof(T)> result; memmove(&result.storage, &value, sizeof(T)); return result; } template<typename T> inline T storage_cast(Storage<sizeof(T)> value) { T result; memmove(&result, &value.storage, sizeof(T)); return result; } template<size_t N> void list_add(Storage<N> s) { printf("impl: %p\n", &list_add<N>); } template<typename T> struct List { inline void add(T v) { list_add(storage_convert(v)); } }; int main() { List<int32_t> a = {}; List<uint32_t> b = {}; List<uint64_t> c = {}; a.add(32); b.add(51); c.add(72); auto d = storage_convert(2); // You can miscast the type if it's the same size auto e = storage_cast<uint32_t>(d); // This is a compile error because it's a different size. //auto f = storage_cast<uint64_t>(d); return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines