当前位置:网站首页>STL notes (II): template and operator overloading
STL notes (II): template and operator overloading
2022-07-25 05:07:00 【Reyn Morales】
STL note ( Two ): Templates 、 operators overloading
Templates
Template specialization ( specific )
#include <iostream>
#include <cstring>
using namespace std;
// Count how many are in the array 2 - Iterator related
int count(int * start, int * over, int n) {
int countNum = 0;
while (start < over) {
if (*start == n) countNum++;
start++;
}
return countNum;
}
// Function templates - Output the maximum of two numbers
template <typename T>
T MyMax(T a, T b) {
return a > b ? a : b;
}
// Template specialization ( specific )
template <>
char * MyMax(char * a, char * b) {
if (strcmp(a, b) > 0) return a;
return b;
}
// Class template - Sum of two numbers
template <typename T>
class Add {
private:
T a;
T b;
public:
Add(T sa, T sb) {a = sa, b = sb;};
void show() {cout << a + b << endl;};
};
// Template specialization ( specific )
template <>
class Add<char *> {
private:
char * a;
char * b;
public:
Add(char * sa, char * sb) {strcpy(a, sa), strcpy(b, sb);};
void show() {cout << strcat(a, b) << endl;};
};
int main()
{
// Count how many are in the array 2
int a[] = {2, 2, 4, 5, 2}; // Containers
int * start = a; // iterator - Start
int * over = a + sizeof(a) / sizeof(int); // iterator - end
cout << count(start, over, 2) << endl;
// Enter the maximum of the two numbers
cout << MyMax(2, 3) << endl;
cout << MyMax(2.2, 3.3) << endl;
cout << MyMax("Relax", "Reyn") << endl;
// Sum of two numbers
Add<int> firstNums(2, 3);
firstNums.show();
Add<double> secondNums(2.2, 3.3);
secondNums.show();
char * str1 = "Reyn";
char * str2 = "Relax";
Add<char *> strs(str1, str2);
strs.show();
return 0;
}
extraction (traits)
#include <iostream>
using namespace std;
// traits technology : Extract the commonness of different classes , In order to deal with
// 1. Define basic class templates
template <typename T>
class PlusTras {};
// 2. Template specialization
template <>
class PlusTras<int>
{
public:
typedef int R;
};
template <>
class PlusTras<double>
{
public:
typedef double R;
};
template <>
class PlusTras<char>
{
public:
typedef int R;
};
// 3. Unified template calling class preparation
template <typename T>
typename PlusTras<T>::R Plus(T a, T b)
{
return a + b;
}
/*
typename:
1. And class Equivalent , Used to declare template parameters
2. Identify in the template “ Embedded dependent type name ”
a. Embedded means defined in a class
b. Dependency refers to the dependency on a template parameter
c. Type name refers to the data type name , Not variable names
*/
class INT {
int a[3];
public:
INT(int sa[]) {for (int i = 0; i < 3; i++) a[i] = sa[i];}
int Sum() {
int s = 0;
for (int i = 0; i < 3; i++) s += a[i];
return s;
}
};
class DOUBLE {
double a[3];
public:
DOUBLE(double sa[]) {for (int i = 0; i < 3; i++) a[i] = sa[i];}
double Sum() {
double s = 0;
for (int i = 0; i < 3; i++) s += a[i];
return s;
}
};
class CHAR {
char a[3];
public:
CHAR(char sa[]) {for (int i = 0; i < 3; i++) a[i] = sa[i];}
int Sum() {
int s = 0;
for (int i = 0; i < 3; i++) s += a[i];
return s;
}
};
template <typename T>
class MyTraits {};
template <>
class MyTraits<INT>
{
public:
typedef int R;
};
template <>
class MyTraits<DOUBLE>
{
public:
typedef double R;
};
template <>
class MyTraits<CHAR>
{
public:
typedef int R;
};
template <typename T>
class Manage // Unified template calling class
{
public:
typename MyTraits<T>::R Sum(T t) {return t.Sum();}
};
int main()
{
cout << Plus(4, 5) << endl;
cout << Plus(4.2, 5.8) << endl;
cout << Plus('Q', 'R') << endl;
int a[] = {1, 2, 3};
char b[] = {'h', 'y', 'i'};
double c[] = {3.3, 5.2, 4.4};
INT in(a);
CHAR ch(b);
DOUBLE dou(c);
Manage<INT> m1; // Manage<INT> It's also a type
cout << m1.Sum(in) << endl; // Common methods are called through the unified interface ,Sum() Is the common operation of all composite types , But the implementation is different
Manage<CHAR> m2; // Manage<CHAR> It's also a type
cout << m2.Sum(ch) << endl; // object (ch) Decision method , The return type is controlled by the composite type (Manage<CHAR> m2) decision
Manage<DOUBLE> m3; // Manage<DOUBLE> It's also a type
cout << m3.Sum(dou) << endl; // If there is another DOUBLE Object of type (fuk), Obviously, you can use m3.Sum(fuk)
return 0;
}
The main target
Extract different class Of Generality , In order to Unified treatment
The core idea
traits rely on Explicit template specialization To put... In the code Fragments that change according to different types Drag it out , Wrap with a unified interface . This interface can contain a C++ Anything that a class can contain , Such as embedded type 、 Member functions 、 Member variables . As a customer Template code , Can pass traits The interface exposed by the template class Indirect access to .
Basic steps
- Define basic template classes
- Template specialization
- Preparation of unified template calling class
| step | thought | The goal is |
|---|---|---|
| Define basic template classes 、 Template specialization | Explicit template specialization | Type difference |
| Preparation of unified template calling class | Wrap with a unified interface | Unified treatment |
summary
Unified template calling class The existence of , It is to deal with composite types in a unified way , For the use of commonalities , It is called based on specific objects , And for the control of return type , Is determined by the specific composite type , The combination of specific composite types and unified template calling classes is also a composite type
It should be noted that , Composite type refers to the type defined by the programmer . besides , It is obvious that there are multiple objects under a type
From a certain point of view , Generality It means different The compound type ( class ) In the same operation ( These operations vary by type )
Essentially , Or a specific object calls a specific method , But through Unified template calling class To control There are necessary type changes , So that it can Call a function uniformly At the same time , There is no need to worry about type related problems
in summary , Dealing with type related problems in different composite types is a necessary condition for extraction , The fundamental purpose of extraction is to call their common methods through a unified interface
operators overloading
#include <iostream>
using namespace std;
// Template and operator overloading
// Knowledge review :
// Cast
// float a = 3.4
// const int & b = a(c); a ---> 3(c) // Cast
// int a = 80;
// const Stu & s1 = a; a ---> ("", 80)s // Using constructors ,Stu s(80);
// Operator overloading
// 1. Member functions - Object call
// 2. Friend function - As parameters , Don't need to call
// 3. Global function
class Stu {
string name;
int score;
public:
Stu(int b = 0, string a = "") // Cast , Pay attention to the exchange order - for example :Stu s(80);
{
name = a;
score = b;
}
Stu(string a = "", int b = 0) // overloaded constructor , You can also change the order of parameters declared by the object
{
name = a;
score = b;
}
/*
bool operator>(int value)
{
return this->score > value; // writing score > value Yes
}
*/
bool operator>(const Stu & another) // const quote , Improve code reuse ; Ensure data authenticity ; Save a space
{
return this->score > another.score;
}
};
template<typename T, typename G>
bool MyGreater(T a, G b)
{
return a > b;
}
int main()
{
// Template and operator overloading
cout << MyGreater(3, 4) << endl;
cout << MyGreater(3, 5.6) << endl;
cout << MyGreater(30, 'y') << endl;
// s1 Have you passed the exam 80 branch ?---> s1 > 80 Instead of s1.score > 80( Non professional )
Stu s1("Reyn", 100);
cout << MyGreater(s1, 80) << endl; // s1.operator > (80)
Stu s2("Lisa", 95);
cout << MyGreater(s1, s2) << endl;
return 0;
}
In the next article , We will introduce C++ I / O in (I / O) flow
边栏推荐
- AUTOSAR from getting started to mastering 100 lectures (105) - protection mechanism of AUTOSAR timing for functional safety
- 深入掌握Service
- Idea2021 installation
- When developing or debugging the IP direct scheme, it should be noted that the host value should be consistent with the direct IP
- Actual combat | record an attack and defense drill management
- 85 distributed project construction
- Teach you three ways to optimize the performance from 20s to 500ms
- Small case of data analysis: visualize recruitment data and view the most needed technologies in the field~
- Valley p2420 let's XOR solution
- Luogu p4281 [ahoi2008] emergency gathering / gathering solution
猜你喜欢
[small program practice] first day

Data link layer protocol -- Ethernet protocol

"Niuke | daily question" inverse Polish expression
[email protected] R & D effectiveness measurement indicators"/>Learning records [email protected] R & D effectiveness measurement indicators
[email protected]研发效能度量指标"/>学习记录[email protected]研发效能度量指标

This low code reporting tool is needed for data analysis

Forwarding and sharing function of wechat applet

The second day of rhcsa summer vacation
![[sht30 temperature and humidity display based on STM32F103]](/img/43/bbc66ab2d56cfa9dc05d795e8fe456.jpg)
[sht30 temperature and humidity display based on STM32F103]

MCU experiment record
随机推荐
956. Highest billboard pressure DP
38 lines of PHP code free import database analysis Linux access log
When image component in wechat applet is used as background picture
Get the parameters of the browser address bar
Information System Project Manager --- Chapter IX examination questions of project human resource management over the years
harbor安装
[small program practice] first day
How to test data in the process of data warehouse migration?
Novel capture practice
Document collaboration tool recommendation
[globally unique ID] how to handle the ID primary key after dividing the database and table?
The 6th "Blue Hat Cup" National College Students' Cyber Security Skills Competition writeup
Delivery practice of private PAAS platform based on cloud native
2022-07-24: what is the output of the following go language code? A:[]int{}; B:[]int(nil); C:panic; D: Compilation error. package main import ( “fmt“ ) f
nacos中哪边有这个列的sql脚本啊?
Getting started with scratch
Li Kou 731. My schedule II
unity 3D物体添加 点击事件
Ffmpeg download and installation
Pikachu vulnerability platform exercise