Difficulty:
Let's start with a question
Template<TypenameT, T * P>
StructA
{};
If there is an int type object I, then for the following code
A <Int, & I> OBJ;
Is this legal?
A: A <Int, & I> OBJ; may be legal or may be invalid.
What can be used as a template parameter? Some built-in types and user types, and some non-types can also be used as template parameters.
One requirement of non-type template parameters is that the compiler can determine the parameters during compilation. In other words, a non-type template parameter must be a compilation constant.
To determine whether this sentence is valid, check whether the returned value of & I is a compilation constant. When I is a global or static object, this statement is correct, because the memory allocation of global and static objects occurs during the compilation period, so the address of I (& I value) it can be determined.
Now it is legal to complete this program.
IntI;
IntMain (){
A <int, & I> OBJ;
}
If the second parameter of this template is a reference, the same is true. However, it is worth noting that these non-type and non-reference template parameters are not left values!
Finally, there are integers, Enum types, pointers, and references that can be used as non-type parameters.
The local user-defined type (Local class) Cannot be used as template parameters. This is because local classes do not have external connections. For example
Template<TypenameT>
ClassTest {};
VoidFun1 ()
{
StructX {};
Test <x>;
}
VoidFun2 ()
{
StructX {};
Test <x>;
}
The above test <x> A; is it the same thing? Because there is no external connection, they are the same thing. The programmer's intention is that two local Classes X are two different class definitions, and test <A> is considered to be two different template instances.
For a local class, it can be said that it is an abnormal form of a sound C ++ system. Without an external connection, it cannot own static data members or template member functions.
// The End