Can a function pointer with a const argument be used as a function pointer with a nonconst argument?

后端 未结 2 1059
野趣味
野趣味 2021-02-19 00:36

Perhaps the title isn\'t clear in itself... I have a function f (provided by some library) that takes as an argument a function pointer of signature void g(int*), i

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 01:34

    You are right, there's no reason C should disallow that call (other than because the C standard says it should). U(*)(T*) should be a sub-type of U(*)(const T*) because int* is a sub-type of const int* through substitutability.

    Why C does not allow this, I don't know.

    As for work-arounds, you can provide a proxy function:

    void foo(const int* x) { ... } // <-- the function you want to pass in
    
    void bar(int* x) { foo(x); } // proxy
    
    f(bar); // instead of f(foo)
    

    The fact that using a safe, standard-compliant proxy like this works at all should be proof enough that the call should have been valid in the first place.

提交回复
热议问题