請參閱下面的代碼
queue<function<void()> > tasks;
void add_job(function<void(void*)> func, void* arg) {
function<void()> f = bind(func, arg)();
tasks.push( f );
}
func是我要添加到的函式,tasks其中有引數是arg.
我該怎么做才能使用std::bind它來系結它的引數,以便它可以分配給 的物件std::function<void()>?
uj5u.com熱心網友回復:
我該怎么做才能使用
std::bind它來系結它的引數,以便它可以分配給 的物件function<void()>?
回傳一個未指定的std::bind可呼叫物件,可以直接存盤在std::function。因此,您只需要
function<void()> f = bind(func, arg); // no need to invoke the callable object
tasks.push( f );
但是,我建議使用 lambdas(自 C 11 起)而不是std::bind.
其次,擁有全域變數也不是一個好習慣。我會提出以下示例代碼。讓編譯器推斷傳遞函式的型別及其(可變引數)引數(函式模板)。
template<typename Callable, typename... Args>
void add_job(Callable&& func, Args const&... args)
{
// statically local to the function
static std::queue<std::function<void()>> tasks;
// bind the arguments to the func and push to queue
tasks.push([=] { return func(args...); });
}
void fun1(){}
void fun2(int){}
int main()
{
add_job(&fun1);
add_job(&fun2, 1);
add_job([]{}); // passing lambdas are also possible
}
查看演示
uj5u.com熱心網友回復:
只是系結它,不要執行它。
function<void()> f = bind(func, arg);
tasks.push( f );
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529842.html
上一篇:即使給出了非剝離版本,GDB也不顯示剝離核心檔案的符號
下一篇:攔截器一二三
