Lor*_*one 0 c++ member-function-pointers function-pointers c++11
我对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);
}
Run Code Online (Sandbox Code Playgroud)
此代码打印:
g的自由函数T是指针-------- g的指针少于指针的函数
(多次)解除引用的自由函数(!!!)G的指针是指针--------少了一个指针就是函数
g的成员函数T是成员函数指针-------- g少了一个指针是成员函数指针
所以(请原谅我一次的问题的开放性):为什么函数和函数指针被如此区别对待,也就是说,为什么前者被威胁为真正的指针而后者呢?有历史原因吗?
如果函数是虚函数,则指向成员函数的指针必须正常工作.在这种情况下,它不能简单地是指向函数的指针,因为它必须根据它所应用的对象的动态类型调度到不同的函数.
它通常包含:
归档时间: |
|
查看次数: |
717 次 |
最近记录: |