Jeffrey Schwab wrote:
[color=blue]
> Thomas Matthews wrote:
>[color=green]
>> Hi,
>>
>> I have a Display class. I would like to write a function that takes a
>> range of objects and displays them. The range would be specified by
>> two forward iterators: start and end (one past start).
>>
>> I created a base class "References" to test this concept. I want[/color]
>
>
> That's a potentially confusing choice of name. "Reference" already
> means something completely different. Consider "Proxy" instead.[/color]
My base class is "Reference". Subclasses are Magazine, Book, etc.
Nothing to do with C++ references or proxies.
[color=blue]
>[color=green]
>> the display function to process either a vector<References> or
>> a list<References>. However, in my compiler (Borland C++ Builder),
>> the std::list has a different iterator type than vector.
>>
>> So how can I write a method to process a range of objects,
>> regardless of the container (assume that the fundamental requirement
>> for a range is forward iteration)?
>>
>> struct Reference
>> {
>> string get_category(void) const;
>> string get_title(void) const;
>> };
>>
>> class User_Interface
>> // : public Singleton<User_Interface>
>> // i.e. User_Interface is a Singleton
>> {
>> void display_references(?????);[/color]
>
>
> The answer to the question you asked, is: Make the type of the
> iterators a template parameter. E.g.:
>
> template< typename For /* forward iterator */ >
> void display_references( For p, For const& end )
> {
> // Do your thing...
> }
>
> The answer to the question you didn't ask is: Don't reinvent the loop.
> Use std::for_each. E.g.:
>
> std::for_each( list.begin( ), list.end( ), display );
>
> std::for_each( vector.begin( ), vector.end ), display );
>
> Hth,
> Jeff[/color]
Personally, I don't see any gain in efficiency or readability with
the std::for_each algorithm; but that is my opinion.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book