Template function of a class

Feb 3, 2013 at 7:40pm
Hello, Everyone!

I want to use a template function of a class.

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "Comparison.h"
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    Comparison c;
    cout << "int:" << endl;
    int ia = 5;
    int ib = 10;
    cout << "max(" << ia << ", " << ib << ") = " << c.max(ia, ib) << endl;
    
    return 0;
}


1
2
3
4
5
6
7
8
9
10
11
#ifndef COMPARISON_H
#define	COMPARISON_H

class Comparison {
public:
    Comparison();
    template <class T>
    T max(T a, T b);
};

#endif	/* COMPARISON_H */ 


1
2
3
4
5
6
7
8
9
#include "Comparison.h"

Comparison::Comparison() {
}

template <class T>
T Comparison::max(T a, T b) {
    return (a > b) ? a : b;
}


But I get the error message:

main.cpp:10: undefined reference to `int Comparison::max<int>(int, int)'


Thank you

Ivan
Last edited on Feb 3, 2013 at 7:43pm
Feb 3, 2013 at 9:00pm
nolyc wrote:
Template definitions go into the same translation unit they are instantiated in, unless your compiler supports the export keyword.

A source file together with all included headers and included source files, less any source lines skipped by preprocessor conditionals, is called a translation unit, or TU. TUs can be separately translated and then later linked to produce an executable program.

tl dr, put the template member function definition in the header file.


PS: you are not using the state of the object, so I don't think it should be a member function
Last edited on Feb 3, 2013 at 9:02pm
Feb 3, 2013 at 9:07pm

ne555, thanks!
Topic archived. No new replies allowed.