没有对模板函数的匹配函数调用

No matching function call to template function

本文关键字:函数调用 函数      更新时间:2023-10-16

我编写的模板函数具有以下签名:

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"没有匹配函数

我做错了什么?

问题是表达式&integers[0]返回一个右值,该右值不能绑定到average模板函数的非常量引用参数。

因此,解决方案是使参数非参考(删除&):

template<class IteratorT>
auto average(IteratorT begin, IteratorT end) -> decltype(*begin)

然后将其称为(尽管它没有那么重要,但&integers[8]似乎调用了未定义的行为,学究般地说):

auto average = sigma::average(integers, integers + 8);

但是,为什么一开始就需要这样一个函数模板呢?您可以将std::accumulate用作:

#include <algorithm> //must include this
auto average = std::accumulate(integers, integers + 8, 0)/8;