C-callback to function template: explicitly instantiate template

后端 未结 3 380
温柔的废话
温柔的废话 2020-12-10 03:18

Premise

I’m using a C library (from C++) which provides the following interface:

void register_callback(void* f, void* data);
void invoke_callback(         


        
3条回答
  •  青春惊慌失措
    2020-12-10 03:47

    This should work:

    template 
    void do_register_callback(T& value) {
       void (*callback)(void*) = my_callback;
       register_callback(reinterpret_cast(callback), &value);
    }
    

    The first line forces the compiler to instantiate that function to generate the address - which you can then happily pass.

    EDIT: Let me throw another option in to this mix. Make my_callback a static member of a class template - something like the following:

    template 
    struct foo
    {
    static void my_callback(void* data) {
        T& x = *static_cast(data);
        std:: cout << "Call[T] with " << x << std::endl;
    }
    };
    

    Now, in your register guy, you don't even need the "cast".

    template 
    void do_register_callback(T& value) {
       register_callback(reinterpret_cast(&foo::my_callback), &value);
    }
    

    It appears that the rule for instantiating class templates is different to function templates - i.e. to take the address of a member of a class, the type is instantiated.

提交回复
热议问题