我正在使用 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()
uj5u.com熱心網友回復:
改變這個:
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
和:
typedef std::function<void ()> THE_FUNCTION;
它會起作用。
LE:當你呼叫 bind 時,這意味著你有一個與你想要的“非常相似”的函式,并用一些提供的“值”填充其余不需要的引數。
https://en.cppreference.com/w/cpp/utility/functional/bind
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384841.html
上一篇:如果數字不是偶數,為什么這個函式回傳“None”?如何在不使用else條件的情況下使其回傳“False”?
下一篇:不確定為什么代碼會重復某些輸出