Passing generic parameters to a generic function in C++: Declare a generic function: Use the template keyword and the type placeholder T. Calling a function with generic arguments: Replace type placeholders with concrete type arguments.
Generic functions allow you to write code that operates on different data types without having to specify Write separate functions for data types. In C++, generic parameters are represented using the type placeholder T
.
To pass generic parameters to a generic function, follow these steps:
template
Key Word and type placeholders to declare generic functions. For example: template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
int x = max<int>(1, 2); // 调用 max<int>,返回 int double y = max<double>(3.14, 2.71); // 调用 max<double>,返回 double
Objective: Write a generic function to print different types of values.
Code:
#include <iostream> template<typename T> void print(T value) { std::cout << value << std::endl; } int main() { print<int>(5); // 打印整数 print<double>(3.14); // 打印浮点数 print<std::string>("Hello"); // 打印字符串 return 0; }
Output:
5 3.14 Hello
The above is the detailed content of How to pass generic parameters in C++ generic function?. For more information, please follow other related articles on the PHP Chinese website!