This question was asked to me in an interview:
Lets say you have a function which can take any kind of arguments and any number of arguments. How would you write a template function for the same?
I do not know the exact answer. could anybody suggest?
A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes. The following function template swaps two items: C++ Copy.
Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.
A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.
They checked your awareness of the upcoming C++ standard. The new feature is called "Variadic templates" and looks like this:
template<typename... Args> void f( const Args&... args )
{
// do something
}
For a more complicated examples see, e.g. this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With