Home > Backend Development > C++ > body text

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

WBOY
Release: 2024-06-06 12:06:56
Original
1058 people have browsed it

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;
}
Copy after login
  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
Copy after login

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;
}
Copy after login

Output:

5
3.14
Hello
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!