Consider the following templated function:
template <template<class, class> class V, class T, class Allocator>
void fn(V<T, Allocator>& v)
{
for (T& t : v) {
std::cout << t << std::endl;
}
}
When I pass it a non-const vector like:
std::vector<int> v{ 1, 2, 3, 4, 5 };
fn(v);
The compiler is happy, and I am happy. However, when I pass fn() a const vector like:
const std::vector<int> v{ 1, 2, 3, 4, 5 };
fn(v);
All hell breaks loose.It will result in a compilation error. With GCC 4.9.2, the error message is:
In function 'int main()':
17:7: error: invalid initialization of reference of type 'std::vector<int>&' from expression of type 'const std::vector<int>'
7:6: note: in passing argument 1 of 'void fn(V<T, Allocator>&) [with V = std::vector; T = int; Allocator = std::allocator<int>]'
I thought that V<T, Allocator>& will be deduced to const std::vector<int, std::allocator<int>>&. However, this is not the case. Why is this so?