據我所知,如何將std :: bind作爲通用引用類型傳遞?
std::bind
完全向前既它包裝可調用對象和參數到該調用對象;std::bind
返回對象本身是可移動和/或可複製的,這取決於可調用對象及其參數是可移動和/或可複製的;- a
std::bind
返回對象可能是嵌套的,在這種情況下,外部返回對象是可移動和/或可複製的,就像綁定其他可調用對象時一樣。
因此,我期望下面的代碼片段編譯好。相反,代碼會在main()
的最後兩條語句中生成編譯器錯誤。
#include <functional>
template<typename HandlerType>
void call_handler(HandlerType&& handler)
{
handler();
}
template<typename HandlerType>
void do_something(HandlerType&& handler)
{
auto f = std::bind(
&call_handler<HandlerType&>,
std::forward<HandlerType>(handler));
f();
}
int main()
{
auto a = [&]() {};
do_something(a);
do_something(std::move(a));
auto b = std::bind([&]() {});
do_something(b); // <- compiler error!
do_something(std::move(b)); // <- compiler error!
}
兩個問題行中的每一個都會在沒有另一個的情況下發生錯誤。爲了消除所有的錯誤,我必須註釋掉這兩行。
這裏的一個樣本誤差,從G ++ 4.9.2在Cygwin中,在調用f()
在do_something()
:
(4 of 103): error: no match for call to ‘(std::_Bind<void (*(std::_Bind<main()::<lambda()>()>))(std::_Bind<main()::<lambda()>()>&)>)()’
下面是從Visual Studio 2013的樣品誤差,在同一行:
1>C:\Program Files (x86)\Microsoft Visual Studio12.0\VC\include\functional(1149): error C2664: 'void (HandlerType)' : cannot convert argument 1 from 'void' to 'std::_Bind<false,void,main::<lambda_2b8ed726b4f655ffe5747e5b66152230>,> '
發生了什麼事?我誤解了std::bind
?
具體地,如何能我
- 綁定一個可調用對象?和
- 通過那
std::bind
返回對象到一個函數採取通用引用?和 - 巢那
std::bind
返回對象在另一個std::bind
?
我的目標是底層的可調用對象及其參數被完美轉發。
編輯:爲了澄清,我想通過引用傳遞包裝的可調用對象,按價值計算它的參數,沒有,所以std::ref
不會幫助,至少,不是一個完整的解決方案。其原因是,我真正的代碼更加複雜,包括使f
std::bind
返回的對象跨線程邊界,並且兩個a
和b
std::bind
返回對象可以走出去的範圍在原來的線程之前call_handler
電話f()
,所以a
和b
需要複製或移入f
,不能僅僅是引用。這就是說,我的問題特別是關於std::bind
和完美的轉發,並且爲了提出一個好問題,我已經提取了一些不需要的東西來重現我提到的特定編譯器錯誤。
的std ::綁定的值取參數,可以使用std ::裁判通過引用 –
@Dieter我編輯我的問題,以顯示我特別希望複製或移動,不使用引用。不過謝謝你。 –