Re: Template parameter that has a template argument list

From: tom_usenet (tom_usenet_at_hotmail.com)
Date: 07/16/04


Date: Fri, 16 Jul 2004 11:25:53 +0100

On 15 Jul 2004 14:56:42 -0700, desh_bakth@yahoo.com (Anand Hariharan)
wrote:

>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?

You can use a template template parameter, but that's not an elegant
solution, and means you Containers must have a specific template
interface (e.g. 1 template paremeter giving the value type).

>I am aware that I could simply write
>
>template <typename Iterator>
>void DoSomething( Iterator Begin,
> Iterator End,
> Iterator Result )
>{
>//...
>}
>
>with the function implicitly assuming that the dereferenced iterators
>yield an integer. This does not seem very elegant to me.

The above is the way to go - a function should be as generic as
possible. Why do you want it to work only for "int"? What properties
of int are you relying on? If you really want to prevent non-int
versions even taking part in overload resolution, you can use
boost::enable_if. e.g.

template <typename Iterator>
typename boost::enable_if<
  boost::is_same<
    int,
    typename std::iterator_traits<Iterator>::value_type>
  void>::type
DoSomething(Iterator begin, Iterator End, Iterator Result)
{
  //...
}

That will only work for iterators over int. But generally you should
make your algorithms as generic as possible, and not restrict it to
int if there is no reason to.

Tom



Relevant Pages