Function with template

0

Someone can help me.

I have to do the following function below.

  

Constructs a function to return the largest value among two numbers,   using template.
The function should contain a maximum of two   parameters.
Actual (actual) parameter values do not   can be changed

#include<stdio.h>
#include<iostream>
using namespace std;

template<class T>

void maior(T *Param1 , T *Param2){

    T aux;

    if(Param1 >= Param2)

      aux = *Param1;

      else

      aux = *Param2;

};

int main()
{
    int aux;

    int num1 = 3 , num2 = 4;

    maior <int>(&num1 , &num2);

    cout<<"O maior valor é:"<< aux <<endl;

I do not know if it's this way.

    
asked by anonymous 15.09.2017 / 22:29

1 answer

3

As you may know, the way to declare functions with templates is:

template <class identificador> declaração_da_função;

So, a function that returns the largest value in two values can be defined as follows:

template <class T>
T GetMax (T a, T b) {
 return (a>b?a:b); //operador condicional ternário
}

To use a template-defined function, simply use a syntax similar to this:

declaração_da_função <tipo do dado> (parâmetros);

So, a program that uses the template above can be written as follows:

#include<iostream>

using namespace std;

template <class T>
T GetMax (T a, T b) {
    return (a>b?a:b); //operador condicional ternário
}

int main()
{
    int num1 = 3 , num2 = 4;
    int maior = GetMax<int>(num1,num2);
    cout<<"O maior valor é:"<< maior <<endl;
}

REFERENCE

    
15.09.2017 / 23:42