Re: Template parameter that has a template argument list

From: Chris Val (chrisval_at_bigpond.com.au)
Date: 07/16/04


Date: 16 Jul 2004 01:58:05 -0700

desh_bakth@yahoo.com (Anand Hariharan) wrote in message news:<d07b1a6a.0407151356.da0a962@posting.google.com>...
> Am trying to write a function that accepts iterators to an (arbitrary)
> container that holds a specific type.
>
> E.g.,
>
> template <typename Container>
> void DoSomething( Container<int>::const_iterator Begin,
> Container<int>::const_iterator End,
> Container<int>::iterator Result )
> {
> //...
> }
>
> As it turns out, the above code will not compile. How do I go about
> writing code to effect this?

There are a couple of ways that I can think of, but
the code gets ugly, and I don't think it is really
necessary to move towards more complexity than required.

Of course, I am speaking of (template template) parameters,
and possibly even some form of traits_type classes.

I can post a small example if you like ?
 
> I am aware that I could simply write
>
> template <typename Iterator>
> void DoSomething( Iterator Begin,
> Iterator End,
> Iterator Result )
> {
> //...
> }

Why don't you use it then :-) ?

> with the function implicitly assuming that the dereferenced iterators
> yield an integer. This does not seem very elegant to me.

Ahhh, but you *can* explicitly pass the template type
to the function if you're concerned:

# include <iostream>
# include <ostream>
# include <vector>

template<typename Iterator>
void DoSomething( Iterator Begin,
                  Iterator End,
                  Iterator Result )
 {
  // ...
 }

class Base{};

int main()
 {
  typedef std::vector<int>::const_iterator VecIntIter;
     VecIntIter Begin, End, Result;
     DoSomething<VecIntIter>( Begin, End, Result );

  // Pass some other type this time...
  typedef std::vector<Base>::const_iterator VecBaseIter;
     VecBaseIter Begin, End, Result;
     DoSomething<VecBaseIter>( Begin, End, Result );

  return 0;
 }

Cheers.
Chris Val



Relevant Pages

  • Re: Maintance of c++ code
    ... iterator constant in the standard, ... template ... template <class Iter_> ... container, some only work with particular containers. ...
    (comp.object)
  • Re: Errors in VC program with gdiplus
    ... template argument list ... : see declaration of 'iterator' ...
    (microsoft.public.vc.mfc)
  • Errors in VC program with gdiplus
    ... template argument list ... : see declaration of 'iterator' ...
    (microsoft.public.vc.mfc)
  • traits help
    ... I am learning template programming and there is a problem about ... Now consider a container and an iterator. ... template <typename T> ...
    (comp.lang.cpp)
  • iterator design help
    ... I am writing an iterator for a container. ... class MyIter ... While MyIter is applied to a template algorithm like std::transform, ...
    (comp.lang.cpp)