可变参数函数(不带参数!)
假设您想在 C++0x 中执行此操作:
size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int(T a0, Tn... an) {
size_t n = is_integer<T>::value ? 1 : 0;
return n + count_int(an...);
}
很好,但感觉没有必要传递参数。不幸的是,这不起作用:
size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int() {
size_t n = is_integer<T>::value ? 1 : 0;
return n + count_int<Tn...>();
}
GCC 抱怨错误:在倒数第二行中没有调用“count_int()”的匹配函数。为什么以及如何解决这个问题? 谢谢。
Let's assume you want to do this in C++0x:
size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int(T a0, Tn... an) {
size_t n = is_integer<T>::value ? 1 : 0;
return n + count_int(an...);
}
Nice, but it feels unnecessary to pass around the arguments. Unfortunately, this does not work:
size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int() {
size_t n = is_integer<T>::value ? 1 : 0;
return n + count_int<Tn...>();
}
GCC complains error: no matching function for call to 'count_int()' in the next-to-last line. Why and how can this be fixed?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个有效:
This works:
它会失败,因为当参数包不包含任何值时,您没有基本情况 - 因为您之前使用的 count_int() 基本情况没有模板化,因此无法使用
调用code>,即使
Tn
为空。这就是它失败的原因。至于如何修复它,我几乎不知道。It fails because you have no base case for when the parameter pack contains no values- as the count_int() base case you used earlier isn't templated and thus cannot be called with
<Tn...>
, even whenTn
is empty. That is why it fails. As to how it can be fixed, I have little idea.这是因为停止条件不是函数模板,因此当您使用空
Tn
调用count_int();
时,非模板函数是没找到。如果您尝试将停止条件更改为模板:
您将收到错误,因为当参数包中有参数时,调用哪个函数是不明确的。
您可以通过将调用转发到模板类来解决此问题,并完全避免递归。像下面这样的东西应该可以工作(尽管我还没有成功做到这一点)
This is because the stopping condition is not a function template so when you call
count_int<Tn...>();
with an emptyTn
the non-templated function isn't found.If you try to change the stopping condition to a template:
You'll get an error since it's ambiguous which function you're calling when you do have parameters in the parameter pack.
You can solve this by forwarding the call the a template class and avoid the recursion altogether. Something like the following should work (although I haven't succeeded to do so yet)