On template and paradigm programming in C + +

Posted by pointsplat on Mon, 28 Feb 2022 17:57:32 +0100

preface

Recently, I have been reading the book "Effective C + +" 55 specific ways to improve program and design. It seems that there are some gains after reading it again and again. These classic books are and read repeatedly. Some ambiguous contents will be understood slowly over time. The first one is to regard C + + as a federal language: C, object oriented C + +, tempote C + +, STL. In the actual project, the template is not used much. You have to look at it again every time you use it. Here is a summary.

1, Generic programming

Programming paradigm and generic programming

Programming paradigm is a typical programming style or mode of a programming language
When Generic Programming was first proposed, its motivation was simple and direct: Inventing a language mechanism that can help implement a general standard container library. The so-called general standard container library is to be able to do, such as using a List class to store all possible types of objects; People familiar with other Object-oriented languages should know that, for example, in Java, this is achieved by storing Object references in the List. Java's single root inheritance plays a key role here. However, single inheritance is too heavy for languages at the bottom of the language chain, such as C + +. In addition, using single root inheritance to implement general containers will also bring problems in efficiency and type safety, which are not consistent with the concept of C + +.
Generic programming is a programming style in which algorithms are written in as abstract a manner as possible, independent of the form of data on which they will be executed. This concept was first proposed by David Musser and Alexander A. Stepanov in 1989.

The role of paradigm programming

In short, the significance and function are:
1. Parameterization of types means that types can be passed like method parameters. This is of great significance.
2. Generics enables the compiler to check types during compilation to improve type safety and reduce exceptions caused by object type mismatch at runtime.
3. Generic method, algorithm reuse.
The conclusion is: abstract the usage of all types, write a general class, and then when the same method needs to be used, pass in the specific type, which will ensure data security in the whole operation process, which is the reuse of different types and the same method.

2, Usage of C + + template (C++11)

1. Function template

1.1 writing method

Templates are instantiated in the program compilation stage to detect de legitimacy. Function templates are usually divided into implicit instantiation and display instantiation
Used with C++11 auto and decltype. A function template is not a function, but an abstraction of a series of functions.

template <class Type parameter 1, class Type parameter 2, ...>
Return value type template name(Formal parameter table)
{
    Function body
}

But for ease of understanding, change the above class to typename

template <typename Type parameter 1, typename Type parameter 2, ...>

An example of a function template:

template<typename T>
T add(T &a,T &b)
{
  T c;
  c =a+b;
  return c
}

1.2 function template specialization

Special case is the writing method:

template <>
Return value type template name(Specific type)
{
    Function body
}

That is to say, a type of template is determined. It is a template for special cases. Its function is that unexpected mismatch will occur when the function is overloaded, Using specialization is equivalent to telling the compiler to match special case templates (template specialization is divided into full template specialization and partial template specialization. Class templates are suitable for two kinds of specialization. Because of the overload characteristics of functions, only all templates can be specialization.)

2. Class template

Type 2.1 formwork

#include<iostream>
#include<string>
using namespace std;
// class template is used to parameterize the type of data required by the class
template<typename T1,typename T2 = int>//Class template can specify a default parameter type, which can be considered as partial specialization
class person
{
public:
	person(T1 name,T2 age)
	{
		this->n_name =name;
		this->n_age =age;
	}
	void printer()
	{
		cout<<"person.n_name:"<<this->n_name<<" "<<"person.n_age:"<<this->n_age<<endl;
	}
private:
	T1 n_name;
	T2 n_age;
};
void main(){
	//Type / / person p// Class templates cannot be derived automatically 
	person<string,int>p1("jojo",20);
	p1.printer();

}

2.2 type template as function parameter

//Class template
template<class NameType, class AgeType>
class Person{
public:
	Person(NameType name, AgeType age){
		this->mName = name;
		this->mAge = age;
	}
	void PrintPerson(){
		cout << "Name:" << this->mName << " Age:" << this->mAge << endl;
	}
public:
	NameType mName;
	AgeType mAge;
};

//Class template as function parameter
void DoBussiness(Person<string,int>& p){
	p.mAge += 20;
	p.mName += "_vip";
	p.PrintPerson();
}

int main(){

	Person<string, int> p("John", 30);
	DoBussiness(p);

	system("pause");
	return EXIT_SUCCESS;
}

2.3 derived classes of class template

#include<iostream>
#include<string>
using namespace std;
template<class nametaype,class agetype >
class person
{
public:
	person(nametaype name,agetype age)
	{
		this->nname = name;
		this->nage =age;
	}
	void showperson()
	{
		cout << "name: " << this->nname<< " age: " << this->nage<< endl;
	}
private:
	nametaype nname;
	agetype nage;
};
//The inheritance template is the type that must be told to the derived class T, otherwise t cannot allocate memory
class teacher:public person<string,int>
{
public:
	teacher(string name,int age):person(name,age){}

};
//Derived classes are also template classes
template<class T1,class T2,class T3>
class teacher1:public person<T2,T3>//User specified type
{
public:
	teacher1(T1 a,T2 name,T3 age):person(name,age){}
	T1 tmp;
	void typeprint()
	{
		cout<<typeid(T1).name()<<endl;//Type of output a
		cout<<typeid(T2).name()<<endl;//Type of output name
		cout<<typeid(T3).name()<<endl;//Type of output
	}
};

void main(){
	teacher1<int,string,int>p1(10,"laowang",20);
	p1.typeprint();
	teacher p2("Sun WuKong",500);
	p2.showperson();
}

3. Variable length formwork

The semantics of the variable parameter template is the same as that of the ordinary template, but the writing method is slightly different. When declaring the variable parameter template, you need to put an ellipsis after typename or class...:

template<typename... Types>

Recursive printing (a typical implementation of information)

void print() {}
template<typename T, typename... Types>
void print(const T& firstArg, const Types&... args) {
	std::cout << firstArg << " " << sizeof...(args) << std::endl;
	print(args...);
}

4. Template meta programming

See the article cited

summary

Tip: finally, after reading many articles on the Internet, I have a lost understanding. I once saw someone say that they used the template to write a production and consumption model in the actual project. Although I knew a little at that time, now it seems suddenly bright.

quote

1, Generic Programming
2,Generic programming idea
3,Significance and function of generics
4,C++11 template meta programming
5,C++11 variable parameter template (function template, class template)

Topics: C++