I watched C++ Type Erasure Demystified - Fedor G Pikus - C++Now 2024, and at 21:07 somebody from the audience mentions, I think, "switch and op code", claiming "that's how std::function works", and Pikus seems to know what that they guy is talking about.
But I don't.
What's that? Can somebody provide an explanation of what technique/pattern/idiom "swith and op code" is, the motivations for it, and an example of how it can be used?
(I'm wildly guessing that "switch" refers to switch-statement.)
I think it came up in one conference but i don't recall which, will post it when i find it.
If you have 3 functions you can store 3 function pointers, which will take 24 bytes on x64 system.
struct s
{
    void(*call_f)(void*);
    void(*copy_f)(void*);
    void(*destruct_f)(void*);
};
You can instead store one function pointer that expects an op-code
enum op_code : char
{
    call_f,
    copy_f,
    destruct_f
};
struct s
{
    void(*united_call)(void*, op_code);
};
Inside this united_call , you can switch over the op-code
void united_call_ex(void* ptr, op_code code)
{
    switch(code)
    {
        case call_f:
          call_function(ptr);
          break;
        case copy_f:
          copy_function(ptr);
          break;
        case destruct_f:
          destruct_function(ptr);
          break;
    }
}
This implementation could reduce the size of std::function, but it has an extra decision that needs to be made at runtime, and implementing the call operator would be harder, because it cannot return (you will have to pass a pointer to a properly aligned buffer that you move the result into, which adds extra operations), so maybe only use it for the copy construct, and delete operations.
It is used in libstdc++ for the copy and destruct, while libc++ seems to use a vtable for the copy and destruct instead, and MSVC stores all the operations in the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With