Re: Need help on a template question
On 2007-07-08 01:05, jianqi.wang@gmail.com wrote:
Hi, everyone, I started learning C++ two weeks ago. I am trying to
play with template with constant expressions for template. So I wrote
a very simple program as follows... There are three files: gfield.h,
gfield.cpp and main.c.
//////////////////////////////////////
// gfield.h
#pragma once
You should use proper include guards to make the code portable.
#include <iostream>
using namespace std;
Don't use this in a header-file, it can cause unexpected behaviour and
hard to find errors.
template <int n>
class gfield
{
public:
explicit gfield(int x):_num(x%n){}
~gfield(void);
int get_value(void) const {return _num;}
private:
int _num;
};
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf);
///////////////////////////
//gfield.cpp
#include "gfield.h"
#include <iostream>
using namespace std;
template <int n>
gfield<n>::~gfield(void)
{
}
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf)
{
os<<gf.get_value()<<endl;
return os;
}
///////////////////////
// main.cpp
#include <cstdlib>
Don't need this one.
#include <string>
#include <cstdio>
Or this.
#include <iostream>
#include "gfield.h"
using namespace std;
main()
{
gfield<2> gf(3);
cout<<gf;
cout<<test_return();
Didn't include this function in the code. Try to always post compilable
(and if possible working) code.
}
The problem I met is that there will be link error : unresolved
external symbol... Basically, the compiler could not find operator <<
and gfield<n>::~gfield(void). However, if I move the definition of
these two function definitions to either main.cpp or gfield.h, it
would work.
Can anyone help me on this? Thank you very much!
Yes, this is a common problem with templates, in theory you should be
able to use the export keyword to solve this, but few compiler support
it. The solution is to put all the code in the header file. See also:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
--
Erik Wikstr?m