help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

duplicate explicit template instantiations disallowed?


From: christopherlmarshall
Subject: duplicate explicit template instantiations disallowed?
Date: 30 Aug 2005 18:44:26 -0700
User-agent: G2/0.2

I am trying to, in effect, compile this file with g++ (version 3.3.4):

template <class T> class A {
public:
   T i;
   A(T i1) : i(i1){}
};
typedef int X;
template class A<int>;
template class A<X>;
int main(){
}

g++ complains thusly:

   error: duplicate explicit instantiation of `class A<int>'

My question is why is this a problem for g++?  Can't it simply ignore
an explicit instantion request when it sees the same one more than
once?

I am trying to use explicit instantiations with my build scripts to
achieve the effect of having the class template declarations in header
files and the class template implementations in cpp files (to avoid
having to put the whole class template in a header file, in other
words).  If, for example, I have A.cpp, B.cpp, and C.cpp, and B uses
the A template as A<int> and C uses it as A<double>, I arrange to
include the instantiations:
   template class A<int>;
   template class A<X>;
in A.cpp before linking A, B, and C together. I do this in an automated
fashion through my build scripts (I put special comments in B and C
that my build script uses to assemble a file, A.temp.inst, that A
includes through #include "A.temp.inst", during the "make depend"
step).

Now, why can't I just arrange to not duplicate my instantiations, you
ask?

There are a few reasons.  Here is one.  Say I am using a typedef to
define the type used in a certain role in a certain class and I want to
leave the option open to change the typedef from char to int and have
everything work either way. I would have to write my code so that it
doesn't care whether the typedef is an int or a char.

It g++ allowed duplicate instantions to exist, it would help me write
programs that needed both A<int> and A<X>, and that would link whether
X was int or char.

My build scripts wouldn't be able to remove the duplicates unless then
knew enough C++ syntax to determine whether two literally different C++
type specifications were equivalent.  My build scripts would have to
fully parse C++ to do that.

Chris Marshall



reply via email to

[Prev in Thread] Current Thread [Next in Thread]