C function templates allow you to create functions that work with multiple data types, improving code reusability. The syntax is: template
How to use function templates in C
Function templates are a powerful feature in C that allow you to create functions that can be used in Functions for multiple data types. This improves code reusability and reduces the amount of duplicate code.
Function template syntax
The syntax of function template is as follows:
template <typename T> 函数名(参数列表) { 函数体 }
where T
is the type parameter. There can be multiple type parameters, separated by commas.
Using function templates
To use function templates, simply specify the type parameters after the function name. For example, the following code declares a template function that calculates the sum of two numbers:
template <typename T> T sum(T a, T b) { return a + b; }
Now you can use this function with any data type, for example:
int x = sum(1, 2); // x 等于 3 double y = sum(1.5, 2.5); // y 等于 4.0
In practice Case
The following is a practical case of using function templates in data structures:
template <typename T> class Stack { private: vector<T> elements; public: void push(T element) { elements.push_back(element); } T pop() { if (elements.empty()) { throw runtime_error("Stack is empty"); } T element = elements.back(); elements.pop_back(); return element; } };
This stack class can use any data type, for example:
Stack<int> intStack; intStack.push(1); intStack.push(2); cout << intStack.pop() << endl; // 输出 2 cout << intStack.pop() << endl; // 输出 1
Conclusion
Function templates are a powerful tool in C to improve code reusability and reduce duplicate code. By understanding the syntax of function templates and using practical examples, you can take advantage of this feature to write more flexible and maintainable code.
The above is the detailed content of How to use function templates in C++?. For more information, please follow other related articles on the PHP Chinese website!