Re: Template instantiation problem, take 2
Kaba wrote:
Hello, I posted this problem to comp.lang.c++, but since I didn't get a
satisfying answer, I decided to post here.
Here is a short snippet of code that does not compile (tested with Vc8
and Comeau). This is because somehow Vector<0> gets instantiated,
What do you mean, somehow? It rather obviously gets
instantiated.
for which the array size goes to 0. However, I don't quite get
it why it gets instantiated in the first place.
Because you use it.
So why does not this compile?
template <int N>
struct Vector
{
int data_[N];
};
template <int HEIGHT, int WIDTH>
struct Matrix
{
};
template <int HEIGHT, int WIDTH>
Vector<WIDTH> operator *(
const Vector<HEIGHT>&,
const Matrix<HEIGHT, WIDTH>&)
{
return Vector<WIDTH>();
}
template <int HEIGHT, int WIDTH>
Vector<WIDTH - 1> operator *(
const Vector<HEIGHT - 1>&,
const Matrix<HEIGHT, WIDTH>&)
{
return Vector<WIDTH - 1>();
}
int main()
{
Matrix<1, 1> transform;
Vector<1> translation;
translation = translation * transform;
This invokes (and thus instantiates) operator*( Vector<1>
const&, Matrix<1, 1> const& ). The return type of this function
is Vector<0>. So instantiating this function triggers the
instantiation of Vector<0> (and the instantiation of Vector<0>'s
copy constructor, but that's no problem here).
return 0;
}
I'm having a hard time seeing what you don't understand. The
compiler does a transitive closure on the templates it
instantiates---instantiating one template will trigger the
instantiation of the template specializations which it uses.
This would seem an obvious implication; implicit instantiation
wouldn't be useful otherwise.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]