Valid C ++ clause 42 and valid clause 42
In this section, we will discuss the differences between the class keyword and the typename keyword, and the impact on the template function.
The following code:
template<class T>T getValue1(T m){ return m * 2;}template<typename T>T getValue2(T m){ return m * 2;}
In the above Code, the roles of class and typename are the same and there is no difference. Therefore, programmers can use class or typename according to their personal habits when declaring a template. However, in some cases, only typename can be used instead of class.
The following code:
# Include <iostream> using namespace std; class Defalut {public: typedef int a ;}; template <typename T> int getValue (T m) {typename T: a a1; // a1 = 0; return a1;} int main () {Defalut d; cout <getValue (d); return 0 ;}
C ++ specifies that only typename and class can be added to the comment line above.
Why does an error occur when the typename program is not added? Let's imagine the following code:
class Defalut{public: typedef int a;};class Defalut{public: static int a;};Defalut::a;
Now let's take a look at the call Defalut: a for two classes with the same name. One returns the int type and the other returns the integer value.
In the template, T: a is used to determine whether the return value or the type. For C ++, typename, without the prefix keyword, is considered as the return value, such as T:, returns a static value. If the keyword typename is added, it is considered to be the return type, for example, typename T: a, and a nested type is returned.
Nested type refers to the type defined in the class or other structures.