Passing (?)constant iterators to function

Jan 17, 2022 at 9:23pm
I don't understand how to know the constant-ness of an iterator. Looking at the error message, it seems to say that the iterators returned by begin() and end() are constant, because when I add "const" to the parameters in print() the error goes away. The documentation doesn't say that begin() and end() return constant iterators. And are they constant references? Or is it that what they're pointing to is constant? Both? Thanks so much for your help. Here's the error:

 
no instance of function template "print" matches the argument list


1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename M> 
ostream& print(M& begin, M& end)
{
   for (; begin != end; ++begin)
   {
      cout << *begin << " ";
   }
   return cout;
}

// main
	list<int> a_list;
	print(a_list.begin(), a_list.end()) << endl;
	return 0;
Last edited on Jan 17, 2022 at 9:25pm
Jan 17, 2022 at 9:29pm
Just don't pass them by reference.
Jan 17, 2022 at 9:38pm
Ok, thank you.
Jan 17, 2022 at 9:41pm
> are they constant references? Or is it that what they're pointing to is constant?
they are temporary objects
you can't bind a non-const reference to a temporary object
1
2
3
4
5
void foo(int &n){
   ++n;
}

foo(a+b); //¿? 
Topic archived. No new replies allowed.