auto
or decltype
for Function Pointer TypesIf we know which function(s) we want to return, we can use decltype
to simplify writing a function pointer return type. For example, assume we have two functions, both of which return a string::size_type
and have two const string&
parameters. We can write a third function that takes a string
parameter and returns a pointer to one of these two functions as follows:
string::size_type sumLength(const string&, const string&);
string::size_type largerLength(const string&, const string&);
// depending on the value of its string parameter,
// getFcn returns a pointer to sumLength or to largerLength
decltype(sumLength) *getFcn(const string &);
The only tricky part in declaring getFcn
is to remember that when we apply decltype
to a function, it returns a function type, not a pointer to function type. We must add a *
to indicate that we are returning a pointer, not a function.
Exercise 6.54: Write a declaration for a function that takes two int
parameters and returns an int
, and declare a vector
whose elements have this function pointer type.
Exercise 6.55: Write four functions that add, subtract, multiply, and divide two int
values. Store pointers to these functions in your vector
from the previous exercise.
Exercise 6.56: Call each element in the vector
and print their result.