template <class T>
时间: 2023-09-29 10:11:15 浏览: 90
这是一个模板类的声明,其中 T 是一个占位符类型,可以代表任何类型。在使用时,需要将具体类型替换到 T 的位置上,例如:
```
template <class T>
class MyTemplate {
public:
T getValue() { return value; }
void setValue(T newValue) { value = newValue; }
private:
T value;
};
int main() {
MyTemplate<int> myInt;
myInt.setValue(42);
std::cout << myInt.getValue() << std::endl; // 输出 42
MyTemplate<std::string> myString;
myString.setValue("Hello, world!");
std::cout << myString.getValue() << std::endl; // 输出 "Hello, world!"
return 0;
}
```
在上面的示例中,我们实例化了两个 MyTemplate 类,分别使用 int 和 std::string 作为 T 的具体类型,并调用了它们的成员函数。由于 MyTemplate 是一个模板类,因此可以使用任何类型作为 T 的具体类型。
相关问题
template<class T>
`template<class T>` 是 C++ 中用于定义模板的一种方式,它表示定义了一个模板类或模板函数,其中 `T` 是一个类型参数,可以在模板中使用。
例如,下面是一个使用 `template<class T>` 定义的模板函数示例:
```c++
template<class T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
```
这个 `swap` 函数可以用于交换任意类型的值,其中 `T` 表示类型参数。在函数体中,可以直接使用 `T` 作为类型来定义变量,从而实现通用性。
另外,还可以使用 `typename` 关键字来定义类型参数,例如:
```c++
template<typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
```
这两种方式的效果是一样的,只是语法上略有不同。
使用模板函数时,需要在函数名后使用尖括号(<>)指定具体的类型参数,例如:
```c++
int a = 10, b = 20;
swap<int>(a, b);
double c = 3.14, d = 2.718;
swap<double>(c, d);
```
这里使用 `swap<int>` 和 `swap<double>` 指定具体的类型参数,从而实现了通用的交换函数。
template <class t>
template <class t> 是 C++ 中的一种模板语法,用于定义一个通用类型。使用这种语法可以在编译时为不同的数据类型生成不同的代码,避免重复编写相同的函数或类。其中,t 是一个占位符,可以在实际使用时替换成具体的数据类型。
阅读全文
相关推荐
















