(23条消息) this->使用_最后冰吻free的博客-CSDN博客
Thu Nov 24 2022 06:08:55 GMT+0000 (Coordinated Universal Time)
Saved by
@leawoliu
#include <iostream>
#include <string>
#include <vector>
template<typename T>
struct Base{
void Bar(){
std::cout<<"base::Bar"<<std::endl;
}
T t{};
};
// global function
void Bar(){
std::cout<<"global"<<std::endl;
}
// 对于类模板,如果它的基类也是依赖与模板参数的化,那么对它而言即使x是
// 继承而来的,使用this->x和x也不一定是等效的
template<typename T>
struct Derived: Base<T> {
void Func(){
this->Bar(); // 使用this->调用父类中函数
Base<T>::Bar(); // 使用Base<T>::作用域
}
void Func1(){
Bar(); // error, Bar()函数永远不会解析为Base中的Bar,会调用其他地方Bar(global)
}
};
void Test(){
Derived<int> d;
d.Func(); // base::Bar;
}
// template关键字使用
template<typename T>
struct MyBase{
template<typename U>
void Bar(){
std::cout<<"base::Bar"<<std::endl;
}
};
// 当依赖模板参数的对象,其对象成员函数也是模板时,
// 调用成员函数时,需要在对象点后面使用template关键字
// 否则成员函数后面的<括号会被编译器理解为小于符号
template<typename T>
void TemplateUse(MyBase<T>& b){
b.template Bar<std::string>();
}
void Test1(){
MyBase<int> b;
TemplateUse<int>(b);
}
int main()
{
Test();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
content_copyCOPY
https://blog.csdn.net/CodeHouse/article/details/126440030
Comments