Why doesn't C++ have a pointer to member funct

2019-02-04 19:05发布

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_fun etc. But why did the designers of C++ decide not to have a 64-bit pointer containing a pointer to the function and a pointer to the object, for example?

What I mean specifically is a pointer to a member function of a particular object of unknown type. I.E. something you can use for a callback. This would be a type which contains two values. The first value being a pointer to the function, and the second value being a pointer to the specific instance of the object.

What I do not mean is a pointer to a general member function of a class. E.G.

int (Fred::*)(char,float)

It would have been so useful and made my life easier.

Hugo

9条回答
萌系小妹纸
2楼-- · 2019-02-04 19:39

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.

查看更多
Deceive 欺骗
3楼-- · 2019-02-04 19:40

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).

查看更多
干净又极端
4楼-- · 2019-02-04 19:42

It does.

For example,

int (Fred::*)(char,float)

is a pointer to a member function of a class Fred that returns an int and takes a char and a float.

查看更多
登录 后发表回答