Hello I'm a little bit confused on the following code that I'm reading out of the book "The C++ Standard Library".
1 2 3 4 5 6 7 8 9 10 11
class C
{
public:
explicit C(const std::string & s); // explicit(!) type conversion from strings.
...
};
std::vector<std::string> vs;
for (const C & elem : vs) { // ERROR, no conversion from string to C defined
std::cout << eleme << std::endl;
}
Now I understand that they are saying that an explicit conversion isn't allowed but what I don't understand is what explicit conversion would be happening if there was one allowed.
Specifically I don't understand the const C & elem syntax. How does this work since the collection holds strings. What would be the syntax for how this:
const C & elem
gets strings. I was thinking it was a class reference that someone how converts to a constructor function pointer or something but i'm really confused. Could someone shed some like on this for me please?
I'm a bit lost as to what your telling me is new syntax. If you answering my question with this:
"which are found based on argument-dependent lookup rules with std as an associated namespace."
I'm still as lost as ever as there is no information on these argument-depend lookup rules.
If your telling me that foreach loops are new syntax I already knew that as I stated above before I stated my question.
std::vector<std::string> vs;
for (const C & elem : vs) {
the range-base for statement is returning objects of type std::string. However the left part of the construction
const C & elem
says that they should be converted to objects of class C. So if there is no such an implicit conversion that is if there is no such a conversion function that the compiler could call it will issue an error. If you will remove the function specifier explicit from the constructor then the code will be compiled because the compiler will be allowed to call this constructor implicitly when it is needed as in the code snip above.