template function in class c++
In C++, a template function is a function that can operate on multiple data types. It allows us to write a single function definition that can be used with different types of data.
To create a template function in C++, follow these steps:
- Start by defining the function prototype. Use the keyword
template
followed by thetypename
keyword or the keywordclass
, followed by the name of the type parameter. For example, to create a template function calledprint
that takes a single parameter of typeT
, the prototype would look like this:
template<typename T>
void print(T value);
- Implement the function definition. Since the function is a template, the definition should be placed in the header file, rather than in a separate implementation file. The function implementation can be written as if it was a regular function, without specifying the actual type of the parameter. For example:
template<typename T>
void print(T value) {
std::cout << value << std::endl;
}
- Use the template function by providing the actual type(s) when calling it. The compiler will generate the necessary function(s) based on the provided type(s). For example:
print(10); // Calls print<int>(10)
print(3.14); // Calls print<double>(3.14)
print("Hello"); // Calls print<const char*>("Hello")
- If needed, you can also specify multiple type parameters for a template function. Simply separate the type parameters with commas in the template definition. For example:
template<typename T, typename U>
void swap(T& a, U& b) {
T temp = a;
a = b;
b = temp;
}
Note that template functions are only instantiated for the types they are actually used with. This means that if you don't use a specific instantiation of the template function, it won't be included in the compiled code, reducing the size of the resulting executable.
That's it! You now have a basic understanding of how to create and use template functions in C++. Let me know if you have any further questions.