How would you create a function template with more than one type parameter?

If you don’t know what a function template is, then it would help if you read our quick refresher on function templates.

You may find yourself needing to use more than one type parameter in a function template. If that ever occurs, then declaring multiple type parameters is actually quite simple. All you need to do is add the extra type to the template prefix, so it looks like this:

// 2 type parameters:
template<class T1, class T2>
void someFunc(T1 var1, T2 var2 )
// some code in here...

Can you have unused type parameters?

No, you may not. If you declare a template parameter then you absolutely must use it inside of your function definition otherwise the compiler will complain. So, in the example above, you would have to use both T1 and T2, or you will get a compiler error.

Do template parameters have to be declared with a “T”?

No, the type parameter can actually be declared with any other identifier that you choose – as long as it not a keyword in C++. Using “T” as the name for the type parameter is traditional, but remember that other names can be used.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.