I am implementing an example from the book "A Tour of C ++" by Bjarne Straustrup. I have a template function for calculating the sum of elements (copied from a book):
template<typename Container, typename Value>
Value sum(const Container& c, Value v)
{
for (auto x : c)
v+=x;
return v;
}
I want to apply it to the Vector template (defined in the book), which has the functions "begin" and "end" to support the for-for loop (copied from the book):
template<typename T>
T∗ begin(Vector<T>& x)
{
return x.size() ? &x[0] : nullptr;
}
template<typename T>
T∗ end(Vector<T>& x)
{
return begin(x)+x.size();
}
when applied to Vector, for example:
Vector<int> v={1,2,3,4};
int s=sum(v, 0);
this leads to a compilation error. However, when I remove const from the sum template function
template<typename Container, typename Value>
Value sum( Container& c, Value v)
it compiles.
1- why it did not work with "const"? If this is a problem with the implementation of "begin", "end", how to implement them?
source
share