Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template for a function

Tags:

c++

templates

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?

like image 499
Vijay Avatar asked May 21 '11 08:05

Vijay


People also ask

How do I create a function template?

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.

What is a function template?

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.

Is a function template a function?

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.

What is template explain with example?

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.


1 Answers

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.

like image 62
Yakov Galka Avatar answered Sep 21 '22 12:09

Yakov Galka