Output iterator's value_type

后端 未结 2 977
旧巷少年郎
旧巷少年郎 2020-12-31 00:15

The STL commonly defines an output iterator like so:

template
class insert_iterator
: public iterator

        
2条回答
  •  情深已故
    2020-12-31 00:55

    The real value type of the iterator could well be the iterator itself. operator* may easily just return a reference to *this because the real work is done by the assignment operator. You may well find that *it = x; and it = x; have exactly the same effect with output iterators (I suppose special measures might be taken to prevent the latter from compiling).

    As such, defining the real value type would be just as useless. Defining it as a void, on the other hand, can prevent errors like:

     typename Iter::value_type v = *it; //useless with an output iterator if it compiled
    

    I suppose this is just the limit of the concept of output iterators: they are objects which "abuse" operator overloading, so as to appear pointerlike, whereas in reality something completely different is going on.

    Your problem is interesting, though. If you want to support any container, then the output iterators in question would probably be std::insert_iterator, std::front_insert_iterator and std::back_insert_iterator. In this case you could do something like the following:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    //Iterator has value_type, use it
    template 
    struct value_type
    {
        typedef IterValue type;
    };
    
    //output iterator, use the container's value_type
    template 
    struct value_type
    {
        typedef typename Container::value_type type;
    };
    
    template 
    void parse_aux(Out out)
    {
        *out = typename value_type::type("a", "b");
    }
    
    template