std :: function的替代方法,用于将函数作为参数传递(回调等) [英] Alternative to std::function for passing function as argument (callbacks, etc.)
问题描述
在使用C ++ 11进行实验时,我偶然发现了这一点。我发现这是一个显而易见的解决方案,但我无法在野外找到任何其他示例,因此我担心我缺少一些东西。
I stumbled across this during my experiments with C++11. I find that it is an obvious solution, but I haven't been able to find any other examples of it in the wild, so I'm concerned that there's something I'm missing.
我指的是这种做法(在 addAsync函数中):
The practice I'm referring to (in the "addAsync" function):
#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?
Is it considered bad practice, or is it non-portable (I've only tried it in MSVC++ 2015)? Also, how does the compiler treat this; by conversion to std::function?
我很想在我的项目中继续使用它,因为它显然在签名中声明了必需的参数类型和返回类型,并接受nullptr作为可选项,并且似乎正当工作(我知道这些是C ++中著名的遗言)。
I would love to keep using this in my projects, as it obviously states the required argument types and return type in the "signature", accepts a nullptr for optionality, and seems to "just work" (I am aware that these are famous last words in C++).
推荐答案
您使用的是原始文件
与 std :: function
不同,这不适用于捕获的lambda或 std :: bind
的结果,或者具有实现 operator()
的通用类类型。
Unlike std::function
, this will not work with a lambda that captures, or with a result of std::bind
, or with a general class type that implements operator()
.
这篇关于std :: function的替代方法,用于将函数作为参数传递(回调等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!