C++ 68 之 类模版作函数的参数

cpp 复制代码
#include <iostream>
// #include <cstring>
#include <string>
using namespace std;

template<class T1, class T2> // 可以设置默认的类型值,后面在使用的时候,就不用再指定类型了
class Students08{
public:
    T1 m_name;
    T2 m_age;
    Students08(const T1 name, T2 age){
        this->m_name = name;
        this->m_age = age;
    }
    void show(){
        cout << "姓名: " << this->m_name << endl;
        cout << "年龄: " << this->m_age << endl;
    }
};

// 1.指定传入类型:使用最广泛
// void sendVal( Students08<string, int > &stu){
//     stu.show();
// }

// 2.参数模板化
template<class T1, class T2>
void sendVal(Students08<T1, T2> &stu)
{
    cout << "T1类型是: " << typeid(T1).name() << endl;
    cout << "T2类型是: " << typeid(T2).name() << endl;
    stu.show();
}

// 3.整个类模版化       T == Students08<string,int>
// template<class T>
// void sendVal(T &stu)
// {
//     // 查看类型的系统函数   typeid(T).name()
//     cout << "T类型是: " << typeid(T).name() << endl;
//     stu.show();
// }


int main()
{
    Students08<string,int> stu1("李四",19);
    sendVal(stu1);
    return 0;
}
相关推荐
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++