Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases one needs to specify the template's argument `types` specifically?

Tags:

c++

templates

// Function declaration.
template <typename T1, 
          typename T2, 
          typename RT> RT max (T1 a, T2 b);

// Function call.
max <int,double,double> (4,4.2)

// Function call.
max <int> (4,4.2)

One case may be when you need to specify the return type.

Is there any other situation which requires the argument types to be specified manually?

like image 793
Aquarius_Girl Avatar asked Aug 29 '11 05:08

Aquarius_Girl


People also ask

What are template arguments enlist types of template arguments?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is the purpose of template parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can default argument be used with template class?

You cannot give default arguments to the same template parameters in different declarations in the same scope. The compiler will not allow the following example: template<class T = char> class X; template<class T = char> class X { };


1 Answers

(1) When there is no argument to the function and still it's a template type, then you may have to specify the arguments explicitly

template<typename T>
void foo ()
{}

Usage:

foo<int>();
foo<A>();

(2) You want to distinguish between value and reference.

template<typename T>
void foo(T obj)
{}

Usage:

int i = 2;
foo(i); // pass by value
foo<int&>(i); // pass by reference

(3) Need another type to be deduced instead of the natural type.

template<typename T>
void foo(T& obj)
{}

Usage:

foo<double>(d);  // otherwise it would have been foo<int>
foo<Base&>(o); // otherwise it would have been foo<Derived&>

(4) Two different argument types are provided for a single template parameter

template<typename T>
void foo(T obj1, T obj2)
{}

Usage:

foo<double>(d,i);  // Deduction finds both double and int for T
like image 194
iammilind Avatar answered Sep 29 '22 00:09

iammilind