为什么 std::function 没有被执行

why std::function is not executed

我正在使用 std::bind 创建一个 std::function 类型并对其进行类型定义,但它的实例不会执行。以下是我的代码:

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()

改变这个:

typedef std::function<void (int, const std::string&)> THE_FUNCTION; 

与:

typedef std::function<void ()> THE_FUNCTION; 

它会起作用。

L.E.: 当你调用 bind 时,这意味着你有一个与你想要的“非常相似”的函数,并用一些提供的“值”填充其余不需要的参数".

https://en.cppreference.com/w/cpp/utility/functional/bind