Explicit conversion from string to class reference?

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?
Last edited on
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 std::string &elem : vs) { 
    std::cout << elem << std::endl;
}


Refer to this http://en.cppreference.com/w/cpp/language/range-for
The syntax is new since C++11
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.
If the explicit conversion was allowed it would be from a string object to a const reference to an object of type C

const C & elem = a const reference to an object of type C
In this code snip

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.

Last edited on
Topic archived. No new replies allowed.