我在C++ 11的實驗中偶然發現了這個問題。我發現這是一個明顯的解決方案,但我一直無法在其他地方找到任何其他示例,所以我擔心有些事情我錯過了。作爲參數傳遞函數的std :: function的替代方法(回調等)
的做法我指的是(在「addAsync」功能):
#include <thread>
#include <future>
#include <iostream>
#include <chrono>
int addTwoNumbers(int a, int b) {
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
return a + b;
}
void printNum(std::future<int> future) {
std::cout << future.get() << std::endl;
}
void addAsync(int a, int b, auto callback(std::future<int>) -> void) { //<- the notation in question
auto res = std::async(std::launch::async, addTwoNumbers, a, b);
if (callback) //super straightforward nullptr handling
return callback(std::move(res));
}
int main(int argc, char** argv) {
addAsync(10, 10, [](std::future<int> number) { //lambda functions work great
addAsync(number.get(), 20, [](std::future<int> number) {
addAsync(893, 4387, printNum); //as do standard functions
addAsync(2342, 342, nullptr); //executes, sans callback
std::cout << number.get() << std::endl;
});
});
std::cout << "main thread: " << std::this_thread::get_id() << std::endl;
return 0;
}
是它認爲不好的做法,或者是不可移植的(我只是嘗試在MSVC++ 2015年) ?另外,編譯器如何處理這個問題。通過轉換爲std :: function?
我很想繼續在我的項目中使用它,因爲它顯然在「簽名」中聲明瞭所需的參數類型和返回類型,接受可選的nullptr,並且似乎「只是工作」(我意識到這些都是C++中的最後一句話)。
@Amadeus:也許這是以問號結束的句子。關於SO的問題有很多。這不是其中的一個。 –
該參數被聲明爲具有函數類型'void(std :: future)',該函數被調整爲函數'void(*)(std :: future )'的指針。 –