How to write a function pointer to a function returning a function pointer to a function?

前端 未结 3 1109
误落风尘
误落风尘 2021-02-14 13:14

I want to assign a function\'s address to a function pointer, but the function to be addressed returns a function pointer with the same signature as itself, causing it to recurs

3条回答
  •  情歌与酒
    2021-02-14 13:36

    Don't use void*, because no guarantee that a void * can hold a function pointer. You can use void(*)() as a workaround:

    typedef void(*void_func)();
    typedef void_func (*func_type) (int);
    void_func arbitraryFunction(int a) {
        // could be this function, or another with the same signature, 
        cout << "arbitraryFunction\n";
        return nullptr;  
    }
    void_func function(int a) {
        // could be this function, or another with the same signature, 
        return (void_func) arbitraryFunction;  
    }
    int main() {
        // your code goes here
        func_type f = (func_type) function(0);
        f(0);
        return 0;
    }
    

    LIVE

    C99 [6.2.5/27]:

    A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

    C99 [6.3.2.3/8]:

    A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.

提交回复
热议问题