我在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 )'的指针。 –