Template Classes

Feb 2, 2014 at 5:26pm
I'm trying to learn template classes but am having some trouble. I keep getting "unresolved external" errors but finally narrowed it down to 1 error.

Minmax<T> Minimum unable to match function definition to an existing declaration
which would mean to me that it's unable to head my function header in MinMax.h but I can't tell why.

I know there is something wrong with my syntax but can't figure out what.

MinMax.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
template<class T>
class MinMax
{
private:
	T value1;
	T value2;
public:
	//MinMax();
	T Minimum(T, T);
	T Maximum(T, T);

};


MinMax.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "MinMax.h"

template <class T>
/*
MinMax<T>::MinMax()
{
}
*/
template <class T>
T MinMax<T>::Minimum(T v1, T v2){
	if (value1 < value2){
		return value1;
	}
	else {
		return value2;
	}

}


main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
#include "MinMax.h"
#include<iostream>
using namespace std;


int main(){
	MinMax<int> object;

	cout<<object.Minimum(5,2)<<endl;


}


Any help with this would be greatly appreciated
Last edited on Feb 2, 2014 at 5:27pm
Feb 2, 2014 at 6:03pm
You cannot define member functions of class templates in .cpp files.
You must define them in the header file.

http://www.parashift.com/c++-faq/templates-defn-vs-decl.html

So put the member function definitions in MinMax.h, either below the class template or inside it (as inline member functions).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <class T>
class Example
{
public:

    int func1(double);

    int func2(char c)
    {
        // ...
    }
};

template <class T>
int Example<T>::func1(double d)
{
    // ...
}


Edit: mistake.
Last edited on Feb 2, 2014 at 6:08pm
Feb 2, 2014 at 9:25pm
nevermind lol.

Thanks a bunch dude everything works great!
Last edited on Feb 2, 2014 at 9:49pm
Topic archived. No new replies allowed.