template parameter passing

I have a function like below
1
2
3
4
5
template <class T , class compare>  // compare will be GreaterAge<Person> here
void Merge(T *a, int p, int q, int r , compare comp)
{
   .... code
}

Now , instead of passing int , i want to make this also as template.
so i tried something like :
1
2
3
4
5
template <class T , class compare> 
void Merge<typename Q>(T *a, Q p, Q q, Q r , compare comp)
{
   ... code
}

and called like :
 
Merge<int>(a,p,q,r,comp);

But it is giving error .

Question 1 :
what is correct way to define it?

Question 2 :
suppose i wanted to pass iterator ,say of a vector or map instead of int .
what would be the correct declaration for that?
1)
1
2
3
4
5
template <typename T , typename  Q, typename compare> 
void Merge(T *a, Q p, Q q, Q r , compare comp)
{
  // ... code
}


2) Same. Just modify code to work with iterators.
You have a function that depends on two templated types (T and compare) and you would like to make a function that depends on three templated types? Add to the list?


If the int's are used as indices to an array, then iterators do not fit in transparently.
1
2
3
4
5
6
int x = 3;
vector<Foo> arr;
vector<Foo>::iterator y = arr.begin() + 3;

arr[ x ]; // Ok
arr[ y ]; // Error 
since i used p,q,r , how does the compiler come to know about the number of instances of Q?
I mean i have passed 5 arguments , but typename is used 3 times.
I mean i have passed 5 arguments , but typename is used 3 times.
But you have three different types inside.

It is common to have less types than arguments. For example this standard function: http://en.cppreference.com/w/cpp/algorithm/reverse
So, from http://en.cppreference.com/w/cpp/language/function_template :
The list of template arguments does not have to be supplied if it can be deduced from context.

made few runs of sample program and found out one more rule :
1) Order of specifying template type do not matter.

Thankyou
> Question 1 :
> what is correct way to define it?
> Question 2 :
> suppose i wanted to pass iterator ,say of a vector or map instead of int .
> what would be the correct declaration for that?

Read up on std::merge() and std::inplace_merge; that should lead you in the right direction.
http://en.cppreference.com/w/cpp/algorithm/merge
http://en.cppreference.com/w/cpp/algorithm/inplace_merge
(There are usage examples at the bottom of the pages).
The list of template arguments does not have to be supplied if it can be deduced from context.

That refers to instantiation.
@JLBorges Right to the point !

thankyou
Topic archived. No new replies allowed.