mercredi 19 septembre 2018

Range-based for loop: why does it compile with vector

This question already has an answer here:

I am seeing a situation where changing the type of vector elements from int to bool makes the code stop compiling. What am I missing?

This code compiles fine:

#include <vector>

int main()
{
    std::vector<int> v(10);
    for (auto& e : v)   e = 1;
}

While for this code, the compiler (VC++ 2017) complains about constness mismatch:

#include <vector>

int main()
{
    std::vector<bool> v(10);
    for (auto& e : v)   e = true;
}

I realize that switching to auto&& fixes the problem, but I would appreciate a good explanation as to why.

Aucun commentaire:

Enregistrer un commentaire