我对 C++ 处理函数指针和成员函数指针的方式感到困惑,所以我在这个示例代码中提炼出我的疑惑:
#include <iostream>
#include <type_traits>
#include <functional>
#include <typeinfo>
using namespace std;
struct asd{ void f(){ } };
void f(){}
template<typename T> void g(T f){
cout<<"T of g is "<<
(is_pointer<T>::value?"pointer":
(is_function<T>::value?"function":
(is_member_function_pointer<T>::value?"member function pointer":
"something else")))<<" -------- ";
typedef typename remove_pointer<T>::type TlessPointer;
cout<<"T of g less a pointer is "<<
(is_pointer<TlessPointer>::value?"pointer":
(is_function<TlessPointer>::value?"function":
(is_member_function_pointer<TlessPointer>::value?"member function pointer":
"something else")))<<endl;
}
int main(){
cout<<"free function ";
g(f);
cout<<endl<<"(multiple times) dereferenced free function (!!!) ";
g(******f);
cout<<endl<<"member function ";
g(&asd::f);
//this won't compile: g(*&asd::f);
}
此代码打印:
free function T of g is pointer -------- T of g less a pointer is function
(multiple times) dereferenced free function (!!!) T of g is pointer -------- T of g less a pointer is function
member function T of g is member function pointer -------- T of g less a pointer is member function pointer
所以(请原谅我一次因为问题的开放性):为什么函数和函数指针的处理如此不同,也就是说,为什么前者被威胁为真正的指针而后者?有历史原因吗?
最佳答案
如果函数是虚函数,指向成员函数的指针必须正确工作。在那种情况下,它不能简单地是指向函数的指针,因为它必须根据它所应用的对象的动态类型分派(dispatch)到不同的函数。
它通常包含:
- 一个标志,表明它是否是虚拟的;
- 如果是非虚拟的,则为“普通”函数指针;
- 如果是虚拟的,函数在 vtable 中的索引(假设虚拟分派(dispatch)是用表实现的)。
关于c++ - 为什么自由函数指针总是指针类型,而成员函数指针实际上不是指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066661/