没有匹配的函数调用模板函数
我编写的模板函数具有以下签名:
template<class IteratorT>
auto average(IteratorT& begin, IteratorT& end) -> decltype(*begin)
我认为这可以正常工作,但显然事实并非如此。我通过传入指向数组开头和结尾的指针来调用该函数:
int integers[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
auto average = sigma::average(&integers[0], &integers[8]);
但是 clang 告诉我它找不到匹配的函数:
错误:没有匹配的函数可调用“
average
”
我做错了什么?
A template function I have written has the following signature:
template<class IteratorT>
auto average(IteratorT& begin, IteratorT& end) -> decltype(*begin)
I thought that this would work fine, but apparently it doesn't. I call the function by passing in pointers to the beginning and end of an array:
int integers[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
auto average = sigma::average(&integers[0], &integers[8]);
But clang tells me that it cannot find a matching function:
error: no matching function for call to '
average
'
What have I done wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于表达式
&integers[0]
返回一个rvalue,它无法绑定到average
模板函数的非常量引用参数。所以解决办法就是让参数成为非引用(去掉
&
):然后调用为(虽然没那么重要,但是
&integers[8]
似乎调用了未定义的行为,迂腐地说):但是为什么你需要这样一个函数模板呢?您可以使用
std::accumulate
作为:The problem is that the expression
&integers[0]
returns an rvalue which cannot be bound to non-const reference parameters ofaverage
template function.So the solution is to make the parameters non-reference (removed
&
):Then call it as (although it is not that important, but
&integers[8]
seems to invoke undefined behavior, pedantically speaking):But why do you need such a function template to begin with? You could use
std::accumulate
as: