Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When must a type used as template argument be complete if it is used internally in a context that requires a complete type? [duplicate]

Tags:

c++

templates

Possible Duplicate:
Incomplete class usage in template

I have a question that has been puzzling me for a couple of hours.

Initially I thought that the type would have to be complete at the point of instantiation, but all compilers I have tried accept the type to still be incomplete at that point, as long as it is defined anywhere in the translation unit.

To illustrate it, the question is about the correctness of this simple program:

template <typename T>
int size() {
   return sizeof(T);   // T is required to be complete in this expression
}
class test;            // test is declared, but incomplete

int main() {
   size<test>();
}
// [1] point of instantiation of size<test>()

class test {};         // Definition of test, now it is complete

According to §14.6.4.1/1 the point of instantiation of size<test> is the line marked as [1], and at that point the type test is still incomplete. If we had tried to perform the sizeof(test) operation there, the compiler would have failed telling us that the type is incomplete. And yet calling a template inside which the type to perform that same exact operation compiles in g++, clang++, comeau and Visual Studio 2010.

Is the previous code really correct? Where in the standard does it support that the type used as argument to the template is considered complete if it is complete anywhere in the same translation unit? Or when must it be complete?

like image 851
David Rodríguez - dribeas Avatar asked Oct 26 '11 00:10

David Rodríguez - dribeas


1 Answers

The template is not compiled until after it is expanded at the end (test is complete by that time).

like image 145
MartyTPS Avatar answered Oct 09 '22 19:10

MartyTPS