Template issues

Hi everyone... here's my issue...

This generic function is in Driver.cpp:

1
2
3
4
5
6
#include "Driver.h"

double Driver::average(const vector<T>& num)
{
       return accumulate(num.begin(), num.end(), 0.0) / num.size();
}


I have declared

1
2
      private:
              template <class T> double average(const std::vector<T>&);


in my driver.h file but i'm getting a

"357 C:\...\Proj\Driver.cpp `T' was not declared in this scope"

with a couple more errors.

Please can someone tell me what i'm leaving out or doing wrong..

Thanks in advance
You forgot the template <class T> before double in the definition of average().

By the way, template functions must be declared and defined in the same file in order to be used.
Thanks helios.. so you're saying this is what it should look like?

1
2
3
4
double Driver::template <class T> average(const vector<T>& num)
{
       return accumulate(num.begin(), num.end(), 0.0) / num.size();
}


but now i'm getting a ...

359 C:\...\Proj\Driver.cpp `template' (as a disambiguator) is only allowed within templates

with ...

359 C:\...\Proj\Driver.cpp expected unqualified-id before '<' token

and ...

359 C:\...\Proj\Driver.cpp expected init-declarator before '<' token .



I think my idea is right.. it's just the syntax that's giving me the middle finger. And i have declared

template <class T> double average(const std::vector<T>&);

in the Driver.cpp as well as per your advice. Thanks.
Last edited on
No. It should look like this:
template <class T> double Driver::average(const vector<T>& num)
(I did say before double.)

[quote]And i have declared template <class T> double average(const std::vector<T>&); in the Driver.cpp as well as per your advice. Thanks.[/code]
You don't understand. The declaration must remain in the header. Otherwise, how are other files goign to know what the function they're calling is supposed to look like? What needs to be moved is the defintion. For some reason I have yet to grasp, template functions must be declared and defined in the same file.
For example, if you do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//header.h
template <typename T> T sum(T a,T b);
//header.cpp
#include "header.h"
template <typename T> T sum(T a,T b){
	return a+b;
}
//main.cpp
#include "header.h"

int main(){
	int a=10,b=20,c=sum(a,b);
	return 0;
}

That code will not compile, because the compiler can't find template function definitions in separate files. One way to get around this is including the .cpp, but that gives problems if the file contains other non-template function definitions. What you need to do, is declare and define the function at the same time:
1
2
3
4
//header.h
template <typename T> T sum(T a,T b){
	return a+b;
}
Thanks again for all your help helios...

You're explanation helped loads as well...

I'll remember to throw you some good karma tonight :)
Topic archived. No new replies allowed.