Chaos IN C ++ :: Template parameters mystery

zhaozj2021-02-16  53

Difficulty:

First think about a question

Template

Struct a

{};

If there is an int type object i, then the following code

A obj;

Is this legitimate?

A: A OBJ; may legal or may not legal.

What can be used as a template parameter? Part of the built-in type and user type, and some non-type things can also be used as template parameters.

One requirement for non-type template parameters is that the compiler can determine the parameters in the compile period. In other words, the non-type template parameters must be a compile period constant.

Is it legal to see if it is legal? Is it a compile period constant. When i is a global or static object, then this statement is correct, because the memory allocation of the global and static object occurs in the compile period, so this address (value) of I can be determined.

Now make up this procedure

INT I;

Int main () {

A obj;

}

If the second parameter of this template is referenced, it is also the same. However, it is worth noting that these non-type, non-reference template parameters are not left value!

Finally, it can be integrated as a non-type parameter, ENUM type, pointer, reference.

The local user-defined type (LOCAL CLASS) cannot be used as a template parameter. This is because the local class does not have an external connection. for example

Template

Class test {};

Void fun1 ()

{

Struct x {};

Test a;

}

Void fun2 ()

{

Struct x {};

Test a;

}

Test a; is it the same thing? Since there is no external connection, they are the same thing, and the original meaning of the programmer is two local class X is two different class definitions, and Test is two different template instances.

For local classes, it can be said that it is a well-deformed of a sound C type system. No external connections cause it to have Static Data MEMBERS, you cannot have Template Member functions, and more.

// the end


New Post(0)