Home  >  Article  >  Backend Development  >  How to pass generic parameters in C++ generic function?

How to pass generic parameters in C++ generic function?

WBOY
WBOYOriginal
2024-06-06 12:06:561037browse

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.

How to pass generic parameters in C++ generic function?

Passing generic parameters in C++ generic functions

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:

  1. Declare a generic function: Use 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;
}
  1. Call a function using generic parameters: Call a generic function by replacing the type placeholder with a specific type argument. For example:
int x = max<int>(1, 2);  // 调用 max<int>,返回 int
double y = max<double>(3.14, 2.71);  // 调用 max<double>,返回 double

Practical case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn