template function

S

saneman

I have this template function:

template <typename V, typename I>
void increasing_sequence(I p, I q) {
int j = 1;
while (p != q) {
*p = V(j);
j++; // increasing
++p;
}
}

I then call it with:

increasing_sequence<int>(v.begin(), v.end());

where v could be a container like std::vector. But why is that call
legal? I only specify one template parameter and the function has two.
 
V

Victor Bazarov

saneman said:
I have this template function:

template <typename V, typename I>
void increasing_sequence(I p, I q) {
int j = 1;
while (p != q) {
*p = V(j);
j++; // increasing
++p;
}
}

I then call it with:

increasing_sequence<int>(v.begin(), v.end());

where v could be a container like std::vector. But why is that call
legal? I only specify one template parameter and the function has two.

The other template argument ('I') is _deduced_ from the function call.
Since you pass both the first and second arguments of the same type,
the compiler can deduce it (and it is 'std::vector<???>::iterator',
unless your vector is 'const', in which case it's the const_iterator).

V
 
I

Ian Collins

Victor said:
The other template argument ('I') is _deduced_ from the function call.
Since you pass both the first and second arguments of the same type,
the compiler can deduce it (and it is 'std::vector<???>::iterator',
unless your vector is 'const', in which case it's the const_iterator).
Also note the first parameter can not be deduced.
 
R

red floyd

Ian said:
Also note the first parameter can not be deduced.

Well, not directly, but there's always
std::iterator_traits<I>::value_type if you don't want to have to specify
the first parameter.
 
K

Kai-Uwe Bux

red said:
Well, not directly, but there's always
std::iterator_traits<I>::value_type if you don't want to have to specify
the first parameter.

Except, in this case, the type I can very well be an output iterator. Then,
std::iterator_traits<I>::value_type could be void and not really convey the
needed information.


Best

Kai-Uwe Bux
 
I

Ian Collins

red said:
Well, not directly, but there's always
std::iterator_traits<I>::value_type if you don't want to have to specify
the first parameter.
Assuming that's what the OP wants...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top