Let’s look at a couple more things you can do using function
. First, we don’t actually have to declare six function<double(double)>
objects in Listing 18.8. Instead, we can use a temporary function<double(double)>
object as an argument to the use_f()
function:
typedef function<double(double)> fdd; // simplify the type declaration
cout << use_f(y, fdd(dub)) << endl; // create and initialize object to dub
cout << use_f(y, fdd(square)) << endl;
...
Second, Listing 18.8 adapts the second arguments in use_f()
to match the formal parameter f
. Another approach is to adapt the type of the formal parameter f
to match the original arguments. This can be done by using a function wrapper object as the second parameter for the use_f()
template definition. We can define use_f()
this way:
#include <functional>
template <typename T>
T use_f(T v, std::function<T(T)> f) // f call signature is T(T)
{
static int count = 0;
count++;
std::cout << " use_f count = " << count
<< ", &count = " << &count << std::endl;
return f(v);
}
Then the function calls can look like this:
cout << " " << use_f<double>(y, dub) << endl;
...
cout << " " << use_f<double>(y, Fp(5.0)) << endl;
...
cout << " " << use_f<double>(y, [](double u) {return u*u;}) << endl;
The arguments dub
, Fp(5.0
), etc., are not themselves type function<double(double)>
, and so the calls use <double>
after use_f
to indicate the desired specialization. Thus T
is set to double
, and std::function<T(T)>
becomes std::function<double(double)>
.
Variadic templates provide a means to create template functions and template classes that accept a variable number of arguments. We’ll look at variadic template functions here. For example, suppose we want a function that will accept any number of parameters of any type, providing the type can be displayed with cout
, and display the arguments as a comma-separated list. For instance, consider this code:
int n = 14;
double x = 2.71828;
std::string mr = "Mr. String objects!";
show_list(n, x);
show_list(x*x, '!', 7, mr);
The goal is to be able to define show_list()
in such a way that this code would compile and lead to this output:
14, 2.71828
7.38905, !, 7, Mr. String objects!
There are a few key points to understand in order to create variadic templates:
• Template parameter packs
• Function parameter packs
• Unpacking a pack
• Recursion
3.15.137.59