如何迭代参数包
我需要用C ++ 14定义一个具有模板参数包的函数。
函数的呼叫者确保args ...
的大小必须是偶数,例如2、4、6 ...,我的功能将传递两到两个函数。
template<typename F, typename F2, typename... Args>
void func(F f, F2 f2, Args&&... params) {
using params_t = std::tuple<Args...>;
auto tp = std::make_tuple(params...);
for (std::size_t i = 0; i < sizeof...(Args); ++i) {
f(std::get<i>(tp));
f2(std::get<++i>(tp));
}
}
// caller
func(f1, f2, "abc", 3, "def", "ppp");
这是不起作用的,因为i
不是恒定的表达式。
我该怎么办?这是使用std :: tuple
迭代参数包的正确和唯一方法?
I need to define a function with template parameter pack with C++14.
The caller of the function makes sure that the size of Args...
must be even, such as 2, 4, 6... And my function will pass them two by two to two functions.
template<typename F, typename F2, typename... Args>
void func(F f, F2 f2, Args&&... params) {
using params_t = std::tuple<Args...>;
auto tp = std::make_tuple(params...);
for (std::size_t i = 0; i < sizeof...(Args); ++i) {
f(std::get<i>(tp));
f2(std::get<++i>(tp));
}
}
// caller
func(f1, f2, "abc", 3, "def", "ppp");
This won't work because i
is not a constant expression.
What could I do? Is it the right and the only way to iterate over a parameter pack with std::tuple
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要使用
std :: tuple
在参数包上迭代,通常您会使用std :: index_sequence
引入一包新的索引,并使用折叠表达式进行实际迭代。类似的东西:但是您也可以通过递归迭代,这在您的情况下可能更容易:
To use a
std::tuple
to iterate over a parameter pack, you would usually use astd::index_sequence
to introduce a new pack of indices, and use a fold expression to do the actual iteration. Something like this:But you can also iterate with recursion, which might be easier in your case:
这是我在2011年有限的C ++的情况下做的类型的样本:
(没有 lambdas nor std :: tuple )
有第一个示例执行参数的简单计数,
和第二个样本,演示了如何在每个参数上应用A fuctor 。
NB:最终
eggs
复制由 ### 在输出中显示。- &gt;没有!
输出应为:
Here is a sample of the the kind of things I do, with my 2011 limited c++ :
(without lambdas nor std::tuple)
There is a first sample performing a simple count of the parameters,
and a second sample demonstrating how to apply a functor on each parameter.
NB : Eventual
Eggs
copy is revealed by ### in the output.--> there is none !
The output should be: