error: when I trying to accept a container type.

I wrote a template function which accepts a vector container type. But I meet compilation error. Where wrong.

1
2
3
4
5
6
//header.h

std::ostream& operator<<(std::ostream& os, const review& rv);

template <typename T>
void show1(const std::vector<T>& v);


1
2
//source1.cpp
show1(books);//books is type struct review 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//source2.cpp


std::ostream& operator<<(std::ostream& os, const review& rv){
using std::endl;

os << rv.title << '\t' << rv.rank << endl;

return os;
}


template <typename T>
void show1(const std::vector<T>& v){

using namespace std;

cout << "Title\tRank\n";

for(const T& x : v)
    cout << x;

cout << endl;
}


You didn't say what error message you get but I guess it's because you define the template in a source file instead of the header file. Templates are a bit special so you more or less have to define them in the header file to work.
You need to ensure the entire definition of the template, including the method definitions, are included in any translation unit that uses the template. You can't just link against an object file containing the definition - you have to include it.

In practice, this means that you should include the entire function definition in the header file, not just the prototype.

Thanks for not telling us what the error message is, by the way. Having to play guessing games makes this so much more fun.
It works! Thank you.
The problem is thtat I treat the template function as a function which can seperate its definition in cpp files.
Last edited on
Topic archived. No new replies allowed.