没有对模板函数的匹配函数调用
No matching function call to template function
我编写的模板函数具有以下签名:
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;
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 从 Android JNI/NDK 代码中的C++函数调用 C 函数
- 如何从前面定义的另一个函数调用函数模板
- 为什么我们不能从具有默认参数的函数调用函数?
- 从其他函数调用函数或将函数作为数组的参数是一种好做法还是坏做法
- 使用c++中定义的头函数调用函数
- 从FORTRAN代码调用的c++函数调用c++函数
- 从函数调用函数时出错"identifier not found"
- 函数A调用函数B,函数B调用函数A,你怎么称呼它
- 函数A调用函数B,反之亦然(为什么不起作用)
- 当C++函数参数列表中有String类型时,我可以使用C程序函数调用C++函数吗
- 从静态函数调用函数指针
- 从 Objective-C 函数调用C++函数不起作用
- 从c++ /CLI函数调用c#函数