相关疑难解决方法(0)

C++函数类型

我在理解函数类型时遇到问题(它们看起来像是a的Signature模板参数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
Run Code Online (Sandbox Code Playgroud)

变量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, …
Run Code Online (Sandbox Code Playgroud)

c++ function-pointers c++11 std-function

18
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

function-pointers ×1

std-function ×1