c++template
时间: 2023-09-14 19:05:09 浏览: 49
C++ templates are a powerful feature of the C++ programming language that allow generic programming. Templates enable the creation of functions and classes that can work with different data types without the need for separate implementations for each data type.
Templates are defined using the keyword "template" followed by a list of template parameters enclosed in angle brackets "< >". The template parameters can be either type parameters or non-type parameters, depending on whether they represent a data type or a value. For example, a type parameter might be used to specify the data type of a container class, while a non-type parameter might be used to specify the size of an array.
Here is an example of a simple function template that returns the maximum of two values:
```c++
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
```
In this example, the "typename" keyword is used to indicate that T is a type parameter. The function can be used with any data type for which the ">" operator is defined.
Templates can also be used to define class templates, which are similar to regular classes but can work with different data types. Here is an example of a simple class template for a stack:
```c++
template<typename T>
class Stack {
public:
void push(T value);
T pop();
private:
std::vector<T> data_;
};
template<typename T>
void Stack<T>::push(T value) {
data_.push_back(value);
}
template<typename T>
T Stack<T>::pop() {
T value = data_.back();
data_.pop_back();
return value;
}
```
In this example, the class template is defined with a single type parameter T. The member functions push and pop are defined outside the class definition using the scope resolution operator "::".
Templates are a powerful tool that can greatly simplify code and make it more reusable. However, they can also be complex and difficult to debug. It is important to use templates judiciously and to thoroughly test them with a variety of data types.