多参模板的介绍
class Set {
public:
Set() {}
Set(int a, bool b, std::string c) : a(a), b(b), c(c) {}
void print() {
std::cout << "abc->" << a << b << c << std::endl;
}
private:
int a;
bool b;
std::string c;
};
// 1. 多参的模板声明;
template<typename ...Args>
// 2. 多参的函数声明
void test(Args...params) {
// 3-1. 多参的调用
Set set(params...);
set.print();
// 3-2. 多参结合std::forward调用
Set set1(std::forward<Args>(params)...);
set1.print();
}
多参模板的实例
template <typename Task, typename... Args>
auto Executor::pushTo(bool front, Task task, Args&&... args) -> std::future<decltype(task(args...))> {
// 去掉参数
auto boundTask =
std::bind(std::forward<Task>(task), std::forward<Args>(args)...);
using PackagedTaskType = std::packaged_task<decltype(boundTask())()>;
// std::packaged_task指针,原型是std::packaged_task<decltype(boundTask())()> p(boundTask)
auto packaged_task = std::make_shared<PackagedTaskType>(boundTask);
// std::promise指针,原型是std::promise<decltypetask(args...))>> p;
auto cleanupPromise = std::make_shared<std::promise<decltype(task(args...))>>();
auto cleanupFuture = cleanupPromise->get_future();
// 指针可以直接值传入
auto translated_task = [packaged_task, cleanupPromise]() mutable {
// Execute the task.
packaged_task->operator()();
// Note the future for the task's result.
auto taskFuture = packaged_task->get_future();
// Clean up the task.
packaged_task.reset();
// Forward the task's result to our cleanup promise/future.
forwardPromise(cleanupPromise, &taskFuture);
};
// 释放packaged task的本地指针,现在唯一的引用在lambda中
packaged_task.reset();
}