Problem using templates

Alright so my teacher said I have to have the header and implementation files separate so I can't combine them. I just posting a test file but this same error keeps popping up when I try to do the problem assigned.

header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef _test

#include <iostream>
using namespace std;

template <class T>

class test
{
public:
	test();
};

#include "test.cpp"
#endif 


implementation
1
2
3
4
template <class T>
test <T>::test()
{
}


this gives me
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1
1>Build started 9/12/2013 4:25:05 PM.
1>InitializeBuildStatus:
1>  Touching "Debug\test.unsuccessfulbuild".
1>ClCompile:
1>  test.cpp
1>c:\users\gau\desktop\test\test.cpp(2): error C2143: syntax error : missing ';' before '<'
1>c:\users\gau\desktop\test\test.cpp(2): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\gau\desktop\test\test.cpp(2): error C2988: unrecognizable template declaration/definition
1>c:\users\gau\desktop\test\test.cpp(2): error C2059: syntax error : '<'
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.36
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


I have tried removing the #include "test.cpp" from the header and putting in
#include "test.h" in the implementation file but that gives me a linker error.

So how do I fix this?
It's usually a good idea to split implementation and definition, however in the case of templates, you must have the implementation in the header. This is because templates are resolved during compile-time, and are not available to the linker.

One work-around that is sometimes used is to use inline (.inl) files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// test.h
#ifndef _test
#define _test

template <class T>
class test
{
public:
    test();
};

#include "test.inl"

#endif 


1
2
3
// test.inl
template <class T>
test<T>::test() {}
Last edited on
Topic archived. No new replies allowed.