#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();
}
this->使用
于 2022-08-20 15:02:40 首次发布