[c++] template advanced


foreword

A template parameter classifies type parameters into non-type parameters. A type parameter is a parameter type name that appears in a template parameter list, followed by a class or typename. A non-type parameter is to use a constant as a parameter of a class (function) template, which can be used as a constant in a class (function) template.

1. Template parameters

A reference to a non-type template parameter, which solves part of our problem,

  1. Floating point numbers, class objects, and strings are not allowed as non-type template parameters.
  2. Non-type template parameters must have a compile-time confirmation result.
namespace ljh
{
    
    
 // 定义一个模板类型的静态数组
	 template<class T =int, size_t N = 10>
	 class array
	 {
    
    
	 private:
	 T _array[N];
	 size_t _size;
	 }
 }
 int main()
 {
    
    
 	ljh::array<int,100> s1;
 	ljh::array<int,70> s2;
 }

Similar to the above situation, when our two stacks need to open up different spaces, if there is no template parameter, we need to write two classes.
If it is a full default class, we also need to call ljh::array<> s1;



Template specialization

When do you need to use it?
When we implement an Is_empty function to determine whether two values ​​are the same. However, since different types may be compared in different ways, we can use specialization at this time, or use the matching principle of templates.

template<class T>
bool Is_empty(T left,T right)
{
    
    
	cout << "hah" << endl;
	return left == right;
}
template<>//特化
bool Is_empty<char*>(char* left,char* right)
{
    
    
	return strcmp(left,right) == 0;
}
//模板的匹配原则
bool Is_empty(char* left,char* right)
{
    
    
	return strcmp(left,right) == 0;
}

int main()
{
    
    
	int left = 0;
	int right = 0;
	//cout << Is_empty(left, right)<<endl;
	char str1[] = "woaini";
	char str2[] = "woaini";
	cout<<typeid(str1).name()<<endl;
	cout << Is_empty(str1, str2) << endl;

	
	return 0;
}

Note that str1 and str2 here are essentially array names. When passing parameters, there is type conversion, so if we change the template function to the following const T& in the above parameter passing process, there will be problems with the specialized version. .

template<class T>
bool Is_empty(const T& left,const T& right)//error!
{
    
    
	cout << "hah" << endl;
	return left == right;
}
template<>
bool Is_empty<char*>(char* left,char* right)
{
    
    
	return strcmp(left,right) == 0;
}


Second, separate compilation

1. Import the library

Solution 1: Explicitly specify instantiation.
insert image description here
insert image description here

Solution 2: Do not separate compilation. Declarations and definitions are in a .h file. Because this way, the address of his function has been confirmed when compiling.


Summarize

Template advanced is here! !

Guess you like

Origin blog.csdn.net/weixin_52344401/article/details/121651105
Recommended