Definition. As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.
A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.
A template is not a class or a function. A template is a “pattern” that the compiler uses to generate a family of classes or functions. In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to “fill in” the template.
template<int N>
struct S
{
void foo()
{
sizeof( S ); // (*)
sizeof( S<N> );
}
};
int main()
{
S<5> s;
s.foo();
return 0;
}
This code compiles fine (VS2010), but i have doubts about (*)
string. S
is not complete type, unlike S<N>
in my opinion then how come the compiler knows its size? What does the standard say about such situation, does it well-formed correct sizeof
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With