C++ 函数类型

标签 c++ c++11 function-pointers std-function

我在理解函数类型时遇到问题(例如,它们显示为 std::functionSignature 模板参数):

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不能赋值,但可以调用。诡异的。那它有什么用呢?

现在,如果我对 typedef 进行 const 限定,我仍然可以使用它来构建更多类型,但显然没有其他用途:

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"

我在这里遇到了语言的哪个偏远角落?这种奇怪的类型是如何被调用的,我可以在模板参数之外使用它做什么?

最佳答案

这是标准中的相关段落。它几乎不言自明。

8.3.5/10

A typedef of function type may be used to declare a function but shall not be used to define a function (8.4).

Example:

typedef void F();
F  fv;         // OK: equivalent to void fv();
F  fv { }      // ill-formed
void fv() { }  // OK: definition of fv

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.

Example:

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++ 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17446220/

相关文章:

python - 在 swig 上包装返回 vector <T>

C++:为结构中的每个成员执行方法调用的方法

c++ - 字符串迭代器不可递减

c - 函数指针是邪恶的吗?

c - 警告 : parameter names (without types) in function declaration [enabled by default]

c# - 在 C# 中获取 'ldftn' 函数指针

c++11正则表达式比python慢

小尺寸微 Controller 上的 C++

c++ - 如果 proc 则终止子进程

协变虚函数的 C++ 规则