Function with template

Asked

Viewed 158 times

0

Folks someone can help me.

I have to do the following function below.

Elaborate a function to return the highest value between two numbers, using template.
The function should contain no more than two formal parameters.
Actual (current) parameter values do not may be amended

#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 don’t know if it’s this way.

  • You didn’t put back in maior, as the comparison is also wrong

  • can explain me better I’m studying on my own, I don’t understand much.

  • Related: https://answall.com/q/57790/64969

  • I searched here on the website for template C++ and came a lot of useful and cool stuff, maybe some of the answers will solve your problem

1 answer

3


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

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

Then, a function that returns the highest value out of 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);

Then, a program that uses the above template 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

  • I had found something similar in a book here, I was researching what the ternary operator was.

  • @Carlosferreira I’ve heard of ternário? https://answall.com/q/17398/64969

  • yes now I know what it is.

  • There is no need to use as GetMax<int>(num1, num2);. Can be used as a normal function call, like: GetMax(num1, num2);. Compiler automatically deducts type

Browser other questions tagged

You are not signed in. Login or sign up in order to post.