extern template class

A

arun

Hello team,

I know that

extern keyword before template class or function delays the
instantiation of that template
declaration.

However,, my question is does this utility only works for creating the
libraries or can I use
this utility without using any libraries.

For example I have three files.

queue.h
one.cc
two.cc

queue.h

******************
template <class T> class Queue {
public:

Queue() {}
~Queue() {}
T t;

};


extern template class Queue<int>;

*******************************

one.cc looks like

*****************
#include "queue.h"


int set(Queue<int> q) {

return q.t;
}

******************

and two.cc looks like

*******************
using namespace std;
#include <iostream.h>
#include "queue.h"

int main(void) {


Queue<int> q;
int a = set(q);

cout <<"The value of a is " << a << endl;

return 0;

}

******************

The whole code does not compile and I get following error by compiler.

********
undefined referenct to Queue<int>::Queue()
undefined referenct to Queue<int>::~Queue()

in function main.

**********

Kindly tell me what am I doing wrong.

Thanks.

arun
 
P

Pete Becker

arun said:
I know that

extern keyword before template class or function delays the
instantiation of that template
declaration.

Actually, it doesn't. That's a common extension, and it's just been
approved for the next version of the C++ language definition. But it's
not required in conforming compilers today, so whatever it actually does
is implementation-specific.
However,, my question is does this utility only works for creating the
libraries or can I use
this utility without using any libraries.

The future standardized version can be used anywhere. It declares that a
template instantiation exists but doesn't force it to be instantiated.
The whole code does not compile and I get following error by compiler.

********
undefined referenct to Queue<int>::Queue()
undefined referenct to Queue<int>::~Queue()

This leads to the same problem:

extern int i;

You've said that you're going to provide a defition somewhere, so you
have to do it:

int i;

Similarly,

extern template class Queue<int>;

is a declaration that says that you're going to provide a definition, so
you have to do it:

template class Queue<int>;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,588
Members
45,095
Latest member
EmiliaAlfo

Latest Threads

Top