-3

I'm learning c++ with some videos, but for some reason when I put tipo from template <class tipo> in a function, it suddenly gives me lots of errors.

#include <iostream>

using namespace std;

template <class tipo>
void dar( tipo dato );

int main(){
    int dat1 = 345;
    float dat2 = 4.435;
    char dat3 = 'a';

    dar( dat1 );
    dar( dat2 );
    dar( dat3 );

    return 0;
}

void dar( tipo dato ){   
    cout<<"el dato es: "<<dato;
}

The errors are: enter image description here

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 2
    And what did the errors say? Which part of the error messages are unclear to you? Can you [edit] your question and add additional information to it. – Sam Varshavchik Jan 17 '21 at 03:29
  • 2
    You also need the template specification when you actually define `dar`, not just when you forward declare it. – Nathan Pierson Jan 17 '21 at 03:32
  • Your definition must also be a template. Usually, programmers define templates right when they are declared – alter_igel Jan 17 '21 at 03:36
  • I believe more research could have been conducted before asking this question. Checking out documentation (e.g. c++ reference) or even a short blog article on templates in c++ would have likely yielded an answer. – Alexander Guyer Jan 17 '21 at 03:39
  • 1
    **DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. [ask] – Rob Jan 17 '21 at 12:04

1 Answers1

4

This is a forward declaration:

template <class tipo>
void dar( tipo dato );

And this is supposed to be the definition:

void dar( tipo dato ){   
    cout<<"el dato es: "<<dato;
}

But it isn't. Instead it's a function (not a function template) taking a tipo by value. There is no type called tipo in the program.

You need to make tipo a template parameter:

template <class tipo>
void dar( tipo dato ){   
    cout<<"el dato es: "<<dato;
}

An easier way to do it is to provide the definition directly at the beginning of the program and skip the forward declaration:

#include <iostream>

// using namespace std; // don't use this even though the video used it. See:
// https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

template <class tipo>
void dar( tipo dato ) {
    std::cout << "el dato es: " << dato << '\n';
}

int main(){
    int dat1 = 345;
    float dat2 = 4.435;
    char dat3 = 'a';

    dar( dat1 );
    dar( dat2 );
    dar( dat3 );
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108