-
Template class parameter
Hello everyone,
Sometimes a template class is defined to have only parameter and no type (e.g. class something) information. Like the below sample. My question is, why define template class in this way (e.g. I can implement in an alternative way to put the parameter into constructor)? If there is no type information (e.g. class something), there will be no benefits and reasons to use the template class. Any comments?
Code:
#include <vector>
#include <iostream>
using namespace std;
template <int size> class Foo {
private:
int limit;
public:
Foo()
{
limit = size;
}
};
int main (int argc, char** argv)
{
Foo <100> f1; // limit member of instance f1 is 100
Foo <200> f2; // limit member of instance f2 is 200
return 0;
}
thanks in advance,
George
-
It allows you to specialize the template based on particular values, and it enables metaprogramming tricks. For instance imagine you had a mathematical vector class called vector<N> where N is the number of dimensions. You might specialize these classes to give them intuitive constructors to supply initial values. For instance:
Code:
vector<1> vec1(1.0);
vector<3> vec2(0.0, 1.0, -3.0);
The 1-dimensional constructor has 1 argument, and the 3-dimensional constructor has 3 arguments. There is no way to do this without specializing on the integral template parameter.
-
As one thing it provides a mean to declare automatic arrays in a class and let the user choose the size of the class:
Code:
template <int max>
class A
{
int array[max];
}
In this case max has to be a compile-time constant and template arguments is the way to pass it to the class. It also allows you to create different instances of the same class that use an array with a different size.
One curious thing is that you can use the template argument throughout the class as a constant, and you don't need to store it as a member (limit in your code).