Why doesn't C++ have a pointer to member function type?

后端 未结 9 1799
一生所求
一生所求 2020-12-30 07:24

I could be totally wrong here, but as I understand it, C++ doesn\'t really have a native \"pointer to member function\" type. I know you can do tricks with Boost and mem_fu

相关标签:
9条回答
  • 2020-12-30 08:24

    The TR1 has std::tr1::function, and it will be added to C++0x. So in a sense it does have it.

    One of the design philosophies of C++ is: you don't pay for what you don't use. The problem with C# style delagates is they are heavy and require language support, that everyone would pay for whether they used them or not. That is why the library implementation is preferred.

    The reason delegates are heavy is that a method pointer is often larger than a normal pointer. This happens whenever the method is virtual. The method pointer will call a different function depending on what base class uses it. That requires at least two pointers, the vtable and the offset. There is other weirdness involved with the method is from a class involved in multiple inheritance.

    All that said, I am not a compiler writer. It may have been possible to make a new type for bound method pointers that would subvert the virtual-ness of method referenced (after all we know what the base class is if the method is bound).

    0 讨论(0)
  • 2020-12-30 08:25

    I think that the answer is that the designers of C++ choose not to have in language the things that could be just as easily implemented in a library. Your own description of what you want gives a perfectly reasonable way to implement it.

    I know it sounds funny, but C++ is a minimalistic language. They did leave to libraries all they could leave to them.

    0 讨论(0)
  • 2020-12-30 08:27

    It occurs to me that methods have an implicit this argument, so a c pointer to a method is insufficient to allow the method to be called (because there is no way to determine which instance should be used for this (or even if any instance is currently extant)).

    Edit: Rocketmagnet comments that he addressed this in the question, and that appears to be the case, though I think that was added after I started this response. but I'll say "mea culpa", anyway.

    So allow me to expand on the thought a bit.

    C++ is closely related to c, and has all its intrinsic types compatible with the earlier language (largely because of the history of c++ development, I suppose). So, a intrinsic c++ pointer is a c pointer, and is incapable of supporting the use you ask for.

    Certainly you could build a derived type to do the job---as in the boost implementation---but such a critter belongs in a library.

    0 讨论(0)
提交回复
热议问题