c++ - 为什么自由函数指针总是指针类型,而成员函数指针实际上不是指针?

标签 c++ c++11 function-pointers pointer-to-member

我对 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/

相关文章:

c++ - 第 N 个四面体数 mod m?

c++ - std::vector在push_back和insert(end(),x)之间不一致崩溃

c++ - 在 STL 映射和列表上迭代的通用循环 (c++)

c++11 - 如何使用 std::shared_ptr 实现多态性?

c++ - 虚拟方法或函数指针

c++ - 非 Qt 应用程序中基于 Qt 的 DLL 中的事件循环

c++ - 在此上下文中的完美转发和 std::move 行为

linux - 如何获得捕捉 SIGABRT 的信号

c++ - 将 mem_fun 与具有多个参数的函数一起使用

c++ - 指向函数和派生类的指针