Directly casting from pointer to a template function?

后端 未结 2 1460
旧时难觅i
旧时难觅i 2021-01-18 14:55

I am trying to take a pointer to an instance of function template and cast it to void*:

#include 

void plainFunction(int *param) {}

template         


        
相关标签:
2条回答
  • 2021-01-18 15:43

    Both are technically wrong: in C++, you can't convert a function pointer to a void*.

    Pointer-to-function types (like void (*)(int*) here) are a completely different class of types than pointer-to-object types (like void* here).

    Visual C++ allowing the conversion at all (e.g. in void* addr1 = &plainFunction;) is a language extension (compiling with the /Za flag, which disables language extensions, causes both lines to be rejected).

    The error is a bit misleading, for sure, though some other compilers are equally unhelpful (Comeau reports "error: no instance of function template "templateFunction" matches the required type").

    0 讨论(0)
  • 2021-01-18 15:54

    Compiler should generate error in both cases. Function pointers are not convertible to void* according to the Standard §4.10/2 since functions are not objects (§1.8/1). Visual Studio 2008 allows this as an extension, check this bug.

    Use typedef to avoid misunderstanding:

    typedef void(func)(int*); // declare func type
    func* addr1 = &plainFunction;         // OK
    func* addr2 = &templateFunction<int>; // OK
    
    0 讨论(0)
提交回复
热议问题