Calling function template specialization using C calling conventions

前端 未结 3 1085
独厮守ぢ
独厮守ぢ 2020-12-05 11:36

I have the following template

template void f(T t) { }

And I want to pass the address of a specific specialization of it

3条回答
  •  悲哀的现实
    2020-12-05 12:09

    What does the C header look like? Somewhere, the C source must enumerate the callback types allowed. You should take that opportunity to have a series of macros that generate prototypes to individual stub functions, with a corresponding sequence of macros in the C++ source generating extern "C" stubs.


    As to the second question: Yes, that works, but the typedef is not inside a template. I attempted to put such a typedef inside a class, but it turns out that even class templates are not allowed inside the extern "C". So you can have a function template, but no parameters of dependent type.

    Merely defining that function is easy:

    extern "C" typedef void ftype(int);
    
    template
    static ftype f; // <- added "static" here
    
    template< typename T >
    void f(int q) {}
    

    Aha, variadic functions!

    extern "C" typedef void ftype( int, ... );
    
    template
    static ftype f;
    
    template< typename T >
    static void f( int z, ... ) {
        va_list va;
        va_start( va, z );
        T v = va_arg( va, T );
        va_end( va );
    
        std::cout << v;
    }
    

    You don't really need type deduction since it's just a callback, so you can pass this & f to the C code, all callbacks having the same type, and it can make the type determination at runtime and pass whatever it wants through the varargs.

提交回复
热议问题