Home > Article > Backend Development > How to use class templates in C++ function templates?
#C Class templates in function templates
C Function templates are aware of class templates and utilize them as parameter types. This allows you to create generic functions that work with a variety of data types and structures.
Syntax
template<typename T> void func(const T& arg1, const T2& arg2, ...);
Where:
T
is the type template of the function parameter. arg1
, arg2
and subsequent parameters are the actual parameters of the function. Practical Case
Consider a function that prints a pair of values of any type:
template <typename T1, typename T2> void print_pair(const T1& a, const T2& b) { std::cout << a << " " << b << std::endl; }
We can apply this function template to Different type combinations:
int main() { print_pair(1, 2.5); // 打印整数和浮点数 print_pair("Hello", "World"); // 打印字符串 return 0; }
In the first example, T1
is deduced to int
and T2
is deduced to double
. In the second example, both T1
and T2
are deduced to std::string
.
Advantages
Function templates using class templates have the following advantages:
The above is the detailed content of How to use class templates in C++ function templates?. For more information, please follow other related articles on the PHP Chinese website!