#include <iostream>
void register_callback(void* f, void* data);
void invoke_callback();
template <typename T>
void my_callback(void* data) {
T& x = *static_cast<T*>(data);
std:: cout << "Call[T] with " << x << std::endl;
}
// Explicit instantiation:
//template void my_callback<int>(void* data);
template <typename T>
void do_register_callback(T& value) {
// Implicit instantiation:
if (false) { my_callback<T>(0); }
register_callback(reinterpret_cast<void*>(static_cast<void(*)(void*)>(my_callback<T>)), &value);
}
int main() {
int ft = 42;
do_register_callback(ft);
invoke_callback();
}
// [ Library ] /////////////////////////////////////////////////////////////////
struct callback_t {
void (*f)(void*);
void* data;
} library_callback_data;
void register_callback(void* f, void* data) {
library_callback_data.f = reinterpret_cast<void(*)(void*)>(f);
library_callback_data.data = data;
}
void invoke_callback() {
(*library_callback_data.f)(library_callback_data.data);
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdm9pZCByZWdpc3Rlcl9jYWxsYmFjayh2b2lkKiBmLCB2b2lkKiBkYXRhKTsKdm9pZCBpbnZva2VfY2FsbGJhY2soKTsKCnRlbXBsYXRlIDx0eXBlbmFtZSBUPgp2b2lkIG15X2NhbGxiYWNrKHZvaWQqIGRhdGEpIHsKICAgIFQmIHggPSAqc3RhdGljX2Nhc3Q8VCo+KGRhdGEpOwogICAgc3RkOjogY291dCA8PCAiQ2FsbFtUXSB3aXRoICIgPDwgeCA8PCBzdGQ6OmVuZGw7Cn0KCi8vIEV4cGxpY2l0IGluc3RhbnRpYXRpb246Ci8vdGVtcGxhdGUgdm9pZCBteV9jYWxsYmFjazxpbnQ+KHZvaWQqIGRhdGEpOwoKdGVtcGxhdGUgPHR5cGVuYW1lIFQ+CnZvaWQgZG9fcmVnaXN0ZXJfY2FsbGJhY2soVCYgdmFsdWUpIHsKICAgIC8vIEltcGxpY2l0IGluc3RhbnRpYXRpb246CiAgICBpZiAoZmFsc2UpIHsgbXlfY2FsbGJhY2s8VD4oMCk7IH0KICAgIHJlZ2lzdGVyX2NhbGxiYWNrKHJlaW50ZXJwcmV0X2Nhc3Q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