How to store various types of function pointers together?

前端 未结 4 522
滥情空心
滥情空心 2021-01-14 18:08

Normal pointers can be stored using a generic void*. e.g.

void* arr[10];
arr[0] = pChar;
arr[1] = pINt;
arr[2] = pA;

Sometime

4条回答
  •  北海茫月
    2021-01-14 18:53

    There are a few things that make up a function pointer's type.

    • the memory address of the code
    • the argument signature
    • the linkage/name mangling
    • the calling convention
    • for member functions, some other stuff too

    If these features aren't uniform across your function pointers then you can't sensibly store them in the same container.

    You can, however bind different aspects into a std::function which is a callable object that only requires the argument signature and return type to be uniform.

    It may be a good time to re-think the problem in terms of virtual functions. Does this mishmash of function pointers have a coherent interface that you can express? If not, then you're doomed anyway :-)

    RE: Hasturkun, you can store heterogeneous function pointers in unions, yes, they're just POD, but you will also need to store information about what type of pointer it is so that you can choose the correct member to call. Two problems with this:

    • there is a per-item overhead,
    • you have to manually check that you're using the right one consistently all the time, this is a burden with nonlocal effects -- it's a spreading poison.

    Far better to have one container per type, it will clarify the code and make it safer. Or, use a proxy such as std::function to make them all have the same type.

提交回复
热议问题