In Templates as I studied we can only have integral arguments i.e int, pointer to other data types and also template template parameter.
But here I am able to pass just a simple class also as a template argument. Is this valid or what I am understanding is wrong. Here is the piece of code.
template <typename T>
class A {
public:
T t;
};
class B {
public:
float f;
};
template <template<typename> class X, class H>
class C {
public:
H obj;
X<int> x;
};
int main()
{
C < A, B > my;
my.obj.f = 2.3f;
my.x.t = 5;
cout << "template class object: " << my.obj.f << endl;
cout << "class object : " << my.x.t << endl;
}
There are three types of template parameters:
int
, std::string
, etc.). In your example, H
is a type parameter;42
). Your example does not contain any of these;A
is a template parameter.In Templates as I studied we can only have integral arguments i.e int, pointer to other data types and also template template parameter.
What you are referring to in the first part of the above sentence applies to the second category of parameters, i.e. non-type parameters, and the last part of the sentence covers template template parameters.
Indeed, a non-type parameter requires values of a specific type, e.g. int
, X*
to be passed as arguments when instantiating the template, and there are severe constraints on:
For instance, this is forbidden:
template<double D>
struct X { /* ... */ };
While this is allowed:
template<int* P>
struct X { /* ... */ };
But constraints are placed on what can be provided as an argument for P
:
int main()
{
int x = 42;
X<&x> obj; // ERROR!
}
The part your sentence above does not cover is the first category (type parameters), and that is actually the one which is most commonly found. Among other things, type parameters are used to instantiate generic collections of objects, such as:
std::vector<my_class> v;