我有一個函數模板,我想完美轉發到一個lambda,我在另一個線程上運行。這裏是你可以直接編譯一個最小的測試用例:完美轉發到異步lambda
#include <thread>
#include <future>
#include <utility>
#include <iostream>
#include <vector>
/**
* Function template that does perfect forwarding to a lambda inside an
* async call (or at least tries to). I want both instantiations of the
* function to work (one for lvalue references T&, and rvalue reference T&&).
* However, I cannot get the code to compile when calling it with an lvalue.
* See main() below.
*/
template <typename T>
std::string accessValueAsync(T&& obj)
{
std::future<std::string> fut =
std::async(std::launch::async,
[](T&& vec) mutable
{
return vec[0];
},
std::forward<T>(obj));
return fut.get();
}
int main(int argc, char const *argv[])
{
std::vector<std::string> lvalue{"Testing"};
// calling with what I assume is an lvalue reference does NOT compile
std::cout << accessValueAsync(lvalue) << std::endl;
// calling with rvalue reference compiles
std::cout << accessValueAsync(std::move(lvalue)) << std::endl;
// I want both to compile.
return 0;
}
對於非編譯的情況下,這裏是錯誤消息是可理解的最後一行:我有一種感覺
main.cpp|13 col 29| note: no known conversion for argument 1 from ‘std::vector<std::basic_string<char> >’ to ‘std::vector<std::basic_string<char> >&’
它可能與如何推斷T&&
有關,但我無法確定故障的確切位置並修復它。有什麼建議麼?
謝謝!
編輯:我用gcc 4.7.0以防萬一這可能是一個編譯器問題(可能不是)
我不確定自己是否正確,但也許C++要求您明確地*在具有複製和移動語義的對象上使用'std :: move'。 –
對不起,我沒有很好地說出這個問題。讓我編輯。簡而言之,我希望這兩個函數實例都能正常工作,並且它們每個都做不同的事情(一個通過傳遞引用來轉發向量,另一個通過每次移動右值引用來向前)。 –
原來,如果你轉換成'(const std :: vector&)',它就可以工作。 –