No matching function call to template function

半世苍凉 提交于 2019-12-12 04:54:28

问题


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?


回答1:


The problem is that the expression&integers[0] returns an rvalue which cannot be bound to non-const reference parameters of average template function.

So the solution is to make the parameters non-reference (removed &):

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

Then call it as (although it is not that important, but &integers[8] seems to invoke undefined behavior, pedantically speaking):

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

But why do you need such a function template to begin with? You could use std::accumulate as:

#include <algorithm> //must include this

auto average = std::accumulate(integers, integers + 8, 0)/8;


来源:https://stackoverflow.com/questions/9351463/no-matching-function-call-to-template-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!