不同的是你不能创建函数类型的对象,但是你可以创建函数指针类型的对象,以及函数引用输入。
这意味着如果你有一个函数,比如f():
void f(){}
那么这里是你可以做的,你不能做的:
FunctionType fun1 = f; //error - cannot create object of function type
FunctionType *fun2 = f; //ok
FunctionTypeR fun3 = f; //ok
测试代码:
typedef void (&FunctionTypeR)();
typedef void FunctionType();
void f(){}
int main() {
FunctionType fun1 = f; //error - cannot create object of function type
FunctionType *fun2 = f; //ok
FunctionTypeR fun3 = f; //ok
return 0;
}
现在查看编译错误(和警告):
prog.cpp: In function ‘int main()’:
prog.cpp:7: error: function ‘void fun1()’ is initialized like a variable
prog.cpp:8: warning: unused variable ‘fun2’
prog.cpp:9: warning: unused variable ‘fun3’
在线演示:http://ideone.com/hpTEv
但是,如果您在函数参数列表中使用FunctionType(这是一个函数类型)为:
void foo(FunctionType bar);
那么就等价于
void foo(FunctionType * bar);
也就是说,无论你写什么,你都可以使用bar来调用函数:
bar(); //ok
(*bar)(); //ok
也就是说,你可以这样写:
void h(FunctionType fun) { fun(); }
void g(FunctionType fun) { (*fun)(); }
演示:http://ideone.com/kwUE9
这是由于函数类型对函数指针类型的调整;也就是说,函数类型被调整变成函数类型的指针:
Function type | Function pointer type (adjusted type)
void () | void (*)()
void (int) | void (*)(int)
int (int,int) | int (*)(int,int)
.... | ... so on
C++03 标准在 §13.1/3 中说,
仅在一个是函数类型而另一个是指向相同函数类型的指针的参数声明是等效。 即函数类型调整为指向函数类型的指针(8.3.5)。
[Example:
void h(int());
void h(int (*)()); // redeclaration of h(int())
void h(int x()) { } // definition of h(int())
void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]
如果你使用`FunctionTypeR(这是一个函数reference类型):
void foo(FunctionTypeR bar);
那么就相当于:
void foo(FunctionType * & bar);
还有,
void h(FunctionTypeR fun) { fun(); }
void g(FunctionTypeR fun) { (*fun)(); }
演示:http://ideone.com/SmtQv
有趣的部分...
您可以使用 FunctionType 来声明一个函数(但不能定义它)。
例如,
struct A
{
//member function declaration.
FunctionType f; //equivalent to : void f();
};
void A::f() //definition
{
std::cout << "haha" << std::endl;
}
//forward declaration
FunctionType h; //equivalent to : void h();
int main() {
A a;
a.f(); //call member function
h(); //call non-member function
}
void h() //definition goes below main()
{
std::cout <<"hmmm.." << std::endl;
}
演示:http://ideone.com/W4ED2