mercredi 29 avril 2020

Is it allowed to pass a pointer to a template function to C library? (as a callback)

Consider the following code:

#include <iostream>

struct Foo {
  void work() { std::cout << "foo" << std::endl; }  
};

typedef void function_type(void *arg);

template <typename T>
void function(void *arg)
{
    auto &t = *reinterpret_cast<T*>(arg);
    t.work();
}

void call_function(function_type *fn, void *arg)
{
    fn(arg);
}

int main()
{
    Foo foo;

    call_function(&function<Foo>, &foo);

    return 0;
}

If call_function() would be an interface of some C library (which is linked dynamically to my program), is it OK to pass a pointer to some specific instance of a template function? Are there any differences between pointers to (a instantiation of) a template function and regular functions?

Aucun commentaire:

Enregistrer un commentaire