Quick actions

cmd+k|ctrl+k

Navigation

Languages

Storage Type Narrowing

Snippet info

Language

Cpp

Visibility

public

Author

evine

Created

2021-05-05T23:49:59.842891Z

Updated

2021-05-06T11:14:50.544879Z

#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;
}
INFO