#include //#include

using namespace std;

template void myswap(type &var_a, type &var_b)//这是一个模板函数myswap,用于交换两个变量的值。它使用了模板参数type,可以接受任意类型的变量作为参数,并通过引用进行交换。 { type tmp = var_a; var_a = var_b; var_b = tmp; cout << 'swap' << endl; }

template<typename type1, typename type2>//这是一个类模板Dog,它有两个模板参数type1和type2。类中包含了一个成员函数show和两个成员变量m_name和m_age,它们的类型由模板参数确定 class Dog { public: void show(); type1 m_name; type2 m_age; };

template<typename type1, typename type2>//这是类模板Dog中成员函数show的定义,它输出成员变量m_name和m_age的值 void Dog<type1, type2>::show() { cout << m_name << ' ' << m_age << endl; }

int main() { Dog<string, int> wc; wc.m_name = 'wc'; wc.m_age = 10; wc.show(); Dog<string, int> ah; ah.m_name = 'ah'; ah.m_age = 20; myswap< Dog<string, int> >(wc, ah); wc.show(); return 0; }

// 解释Dog<string, int> wc; 括号里面为什么是string和int // 解释myswap< Dog<string, int> >(wc, ah); 内容

在代码中,Dog是一个类模板,它有两个模板参数 type1 和 type2。这两个模板参数确定了类中成员变量 m_name 和 m_age 的类型。

在 main 函数中,我们创建了一个 Dog<string, int> 类型的对象 wc。这里的 <string, int> 是模板实参,它指定了 type1 为 string 类型,type2 为 int 类型。因此,wc 对象的 m_name 的类型为 string,m_age 的类型为 int。

在调用 myswap 函数时,我们使用了模板实参 < Dog<string, int> >,这里的 Dog<string, int> 表示我们要交换的变量的类型是 Dog<string, int>。所以,myswap 函数接受的参数类型也是 Dog<string, int>。

C++ 模板编程:使用模板类和模板函数

原文地址: https://www.cveoy.top/t/topic/qtBG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录