问题描述
我目前正在尝试了解可变参数模板支持可以做的一些事情。假设我有这样的功能-
I'm currently trying to get my head around some of the things I can do with variadic template support. Let's say I have a function like this -
template <typename ... Args>
void foo(Args ... a)
{
int len = sizeof...(tail);
int vals[] = {a...};
/* Rest of function */
}
/* Elsewhere */
foo(1, 2, 3, 4);
此代码有效,因为我事先假设参数将是整数,但如果我提供,显然会失败其他的东西。如果我知道参数包会预先包含特定类型,是否有某种方法可以使我无需模板,并且具有-
This code works because I assume beforehand that the arguments will be integers, but obviously will fail if I provide something else. If I know that the parameter packs will contain a particular type in advance, is there some way that I can do without the templating and have something like -
void foo(int ... a)
我尝试这样做,但是编译器给出了有关foo为空字段的错误。我知道我也可以通过递归访问包中的参数,但是我不确定这是否可以解决我遇到的问题-也就是说,我希望能够采用可变数量的相同类型的参数。
I have tried doing this, but the compiler gave an error about foo being a void field. I know that I can also access the parameters in the pack through recursion, but I'm not sure this will fix the problem that I have - namely I want to be able to take a variable number of arguments of the same type.
推荐答案
这应该有效:
void foo(int);
template<typename ...Args>
void foo(int first, Args... more)
{
foo(first);
foo(std::forward(more)...);
}
这篇关于已知类型的C ++可变函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!