C ++函数类型 [英] C++ function types
问题描述
我有一个理解函数类型的问题(它们例如作为 std :: function
Signature >):
I have a problem understanding function types (they appear e.g. as the Signature
template parameter of a std::function
):
typedef int Signature(int); // the signature in question
typedef std::function<int(int)> std_fun_1;
typedef std::function<Signature> std_fun_2;
static_assert(std::is_same<std_fun_1, std_fun_2>::value,
"They are the same, cool.");
int square(int x) { return x*x; }
Signature* pf = square; // pf is a function pointer, easy
Signature f; // but what the hell is this?
f(42); // this compiles but doesn't link
变量 f
不能分配,但可以调用。奇怪的。
The variable f
can not be assigned, but can be called. Weird. What is it good for, then?
现在如果我const-qualify的typedef,我仍然可以使用它来构建更多的类型,但显然没有别的:
Now if I const-qualify the typedef, I can still use it to build further types but apparently for nothing else:
typedef int ConstSig(int) const;
typedef std::function<int(int) const> std_fun_3;
typedef std::function<ConstSig> std_fun_4;
static_assert(std::is_same<std_fun_3, std_fun_4>::value,
"Also the same, ok.");
ConstSig* pfc = square; // "Pointer to function type cannot have const qualifier"
ConstSig fc; // "Non-member function cannot have const qualifier"
这里?
推荐答案
这是一个奇怪的类型,它是如何在模板参数之外使用的? 。
Here's the relevant paragraph from the Standard. It pretty much speaks for itself.
8.3.5 / 10
8.3.5/10
函数类型的typedef可用于声明函数,但不能用于定义函数(8.4)。
A typedef of function type may be used to declare a function but shall not be used to define a function (8.4).
示例:
typedef void F();
F fv; // OK: equivalent to void fv();
F fv { } // ill-formed
void fv() { } // OK: definition of fv
其声明符包含 cv-qualifier-seq 的函数类型的typedef将仅用于声明非静态成员函数的函数类型,声明指向成员的指针的函数类型,或者声明另一个函数typedef声明的顶层函数类型。
A typedef of a function type whose declarator includes a cv-qualifier-seq shall be used only to declare the function type for a non-static member function, to declare the function type to which a pointer to member refers, or to declare the top-level function type of another function typedef declaration.
示例:
typedef int FIC(int) const;
FIC f; // ill-formed: does not declare a member function
struct S {
FIC f; // OK
};
FIC S::*pm = &S::f; // OK
这篇关于C ++函数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!