i'm now writing my first project that actually REQUIRES the use of template classes.
the soon i finished the class i wanted to define some typenames that will be commonly used, but that really got me wondering:
does the key word "typedef" by itself instantiates the template class?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <typename TYPE>
class C
{
TYPE var;
public:
C() {}
~C() {}
};
typedef C<int> my_class_as_int;
int main()
{
return 0;
}
does this code by itself create an (int) instance of the template?
this question might seem silly, but i really feel more comfortable when dealing with things i fully understand.
does the key word "typedef" by itself instantiates the template class?
No, explicit instantiation uses different syntax and implicit instantiation only happens under these conditions:
class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program
this means you can even create my_class_as_int* p; and it still won't be instantiated.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <typename TYPE>
class C
{
typename TYPE::member_type x;
};
typedef C<int> my_class_as_int;
int main()
{
my_class_as_int* mp; // compiles fine
// my_class_as_int mp; // ERROR :error: type 'int' has no members
// in instantiation of template class 'C<int>' requested here
}
EDIT :
i was just reading an example where it used:
1 2 3 4 5
template <typename TYPE>
class C
{
typename TYPE::iterator t;
};
in this example, it was clearly intended to be used with user defined (or standard class) types that defines its own iterator type.
but i want a template that can be used with basic integral types.
does these types implicitly define member_type??
EDIT 2 :
oh sorry, i get it now.
the error at line 12 is because int doesn't define an inner class called member_type and the template you created wasn't meant for simple types after all.
anyway, thank you for the fast reply.
the template you created wasn't meant for simple types after all.
Right, it's purposefully a template that can't be instantiated with TYPE=int, and if typedef alone was instantiating it, it would have failed on line 7 already.