Is conversion allowed with std::vector's template constructor taking iterators?

后端 未结 3 346
终归单人心
终归单人心 2020-12-11 14:57

In the C++11 standard, Section 23.3.6.2 [vector.cons], the following is said:

   template 
     vector(InputIterator first, InputI         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 15:41

    Since the compiler cannot distinguish between the attempt to use copy constructor of type X and the attempt to use a constructor which takes X, any implementation of

    template vector(InputIterator first, InputIterator last, const Allocator& = Allocator());

    has to work in all compilers.

    [Edit] Looks like this needs more explanation. How do I implement the above Vector constructor?

    template 
    vector(InputIterator first, InputIterator last,
                const Allocator& = Allocator())
    {
     for(InputIterator i = first; i != last; i++)
     {
       push_back(*i);  // Or whatever way to add to vector.
     }
    } 
    

    Now any de-reference and attempt to add it local container storage *i will result in a copy constructor of the type *i (let us say type T (i.e, vector). In other words the implementation has to make a copy of the object *i and add it to the internal object collection(whatever it is). So, the template definition/implementation will be finally expanded to something like "T x(*i)". Here on wards it is just a language aspect. C++ doesn't distinguish if *i is of actually type T or *i is a type that can be implicitly converted to T.

    This need not be explicitly stated in a standard.

提交回复
热议问题