【发布时间】:2023-03-25 14:36:02
【问题描述】:
我正在使用 std::bind 创建一个 std::function 类型并对其进行 typedef,但它的实例不会执行。以下是我的代码:
void func(int a, const std::string& b)
{
std::cout << a << ", " << b << std::endl;
}
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
THE_FUNCTION f = std::bind(func, 18, std::string("hello world"));
f; // no action at all
f(); // will not compile, term does not evaluate to a function taking 0 arguments
// class does not define an 'operator()' or a user defined conversion operator
// to a pointer-to-function or reference-to-function that takes appropriate number
// of arguments
f.operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()'
// : non-standard syntax; use '&' to create a pointer to member
(&the_f)->operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()': non-standard syntax; use '&' to create a pointer to member
但是如果我这样做,那么函数就会被执行:
auto g = std::bind(func, 3, "good morning")
g()
【问题讨论】:
-
当您执行
void (int, const std::string&)时,您是在告诉std::funtion它是operator()将返回void并具有参数int和const std::string&。 -
但是如果调用这个函数,整数和字符串都会被打印出来。事实上,没有打印任何东西。我把breaker指针放在func里,并没有停在那里。
-
f;是无操作的;你实际上并没有打电话给任何东西。f()尝试调用某些东西 - 但正如您所注意到的,它没有编译,因为您告诉f期望两个参数但没有传递任何参数。std::bind(func, 18, std::string("hello world"))产生一个不带参数的可调用对象;您可能打算将其分配给std::function<void()> -
它没有被执行,因为除了一个例子之外,它甚至不会编译。编译的本质上是一个空语句无操作。换句话说,
std::function<void()> f = std::bind(func, 18, std::string("hello world")));然后f();应该可以工作。 -
再一次,那将是
std::function<void()>。注意括号。