std::函数的G++问题

G++ problems with std::function

本文关键字:问题 G++ 函数 std      更新时间:2023-10-16

我有以下代码:

#include <functional>
std::function<int,int> p;
int main()
{
return 0;
}

我使用的是MinGW g++4.8.1,失败

C:main.cpp|4|error: wrong number of template arguments (2, should be 1)|
c:mingwlibgccmingw324.8.1includec++functional|1866|error: provided for 'template<class _Signature> class std::function'|
C:main.cpp|4|error: invalid type in declaration before ';' token|

这是一个G++错误,还是我使用std::函数不正确

函数的std::function<int(int)>取int并返回int。例如
int foo(int);

函数的std::function<void(int,int)>取两个int并且没有返回值。例如

void foo(int, int);

std::function采用一个模板参数,即它所封装的可调用对象的类型。因此,如果您想构造一个返回类型Ret并接受类型Arg1, Arg2,..., ArgN的参数的std::function,那么您应该编写std::function<Ret(Arg1, Arg2,..., ArgN)>

(请注意,省略号并不是用来表示参数包扩展的,它们只是在常规数学意义上使用的。)

正如编译器所说,std::函数接受一个模板参数。

使用语法returntype(argtype,…)

int foo(int a, int b) { return a+b; }
std::function<int(int,int)> p = foo;
int bar(int a) { return ++a; }
std::function<int(int)> q = bar;
void boo() { return; }
std::function<void()> r = boo;