[英]Expand variadic arguments in initializer list fails
I try to create a simple program in which I want to create vector of future arguments. I created a wrapper function which is used to submit lambda functions and stores internally in a vector the future objects我尝试创建一个简单的程序,我想在其中创建未来 arguments 的向量。我创建了一个包装器 function,用于提交 lambda 函数并在向量内部存储未来对象
I use an intermediate step in which I create an initiliazer_list using variadic arguments. But fails to compile.我使用了一个中间步骤,在该步骤中我使用可变参数 arguments 创建了一个 initiliazer_list。但无法编译。 I try to use to call a function in order to push the elements in the vector and fails to compile as well
我尝试使用调用 function 来推送向量中的元素,但也无法编译
Below is the code下面是代码
#include <iostream>
#include <thread>
#include <future>
#include <functional>
#include <cstdlib>
#include <chrono>
#include <initializer_list>
using namespace std;
using FunctPtr = function<int(int, int) >;
using FutureInt = future<int>;
using AsyncVector = vector<FutureInt>;
AsyncVector asyncVec;
template<typename... TemplatePtr>
void submit(TemplatePtr... pFunc)
{
auto initList {pFunc... };
for (auto & element : initList)
{
asyncVec.emplace_back(async(launch::async, element,4,5));
}
}
int main()
{
int a;
int b;
auto addPtr = [](int x, int y)->int
{
std::cout << "add :" << x + y << std::endl;
return x + y;
};
auto multPtr = [](int x, int y)->int
{
std::cout << "mult :" << x * y << std::endl;
return x * y;
};
// submit(add,4,5);
submit(addPtr, multPtr);
for (auto & v : asyncVec)
{
std::cout << "Wait for " << v.get() << std::endl;
}
}
Yes, they are of different types so cannot be in the same init-list easily.是的,它们是不同的类型,所以不能轻易地在同一个初始化列表中。
Your best options should probably be:您最好的选择可能应该是:
asyncVec
in the same fold-expression.asyncVec
中。template<typename... TemplatePtr>
void submit(TemplatePtr... pFunc)
{
(asyncVec.emplace_back(async(launch::async, std::move(pFunc), 4, 5)), ...);
}
std::function
.std::function
的数组中。template<typename... TemplatePtr>
void submit(TemplatePtr... pFunc)
{
for (auto &&element: {std::function<int(int, int)>(std::move(pFunc))...})
{
asyncVec.emplace_back(async(launch::async, std::move(element), 4, 5));
}
}
(I have specified function signature explicitly though compiler should be able to deduce it.) (我已经明确指定了 function 签名,尽管编译器应该能够推断出它。)
submit
:submit
时将它们转换为相同的类型:using SameType = int (*)(int, int);
submit(static_cast<SameType>(addPtr), static_cast<SameType>(mulPtr));
This way your original submit
should work as is.这样您的原始
submit
应该按原样工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.