What are the existing rules for taking function pointers or member function pointers to Standard functions? For example, something like
auto p = &std::string::size;
Is this legal? Would it be more or less legal if I explicitly requested the correct type, so it would function even if there was an additional implementation-added overload of std::string::size
?
1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. 2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers. 3) A function's name can also be used to get functions' address.
Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.
C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type. Following is a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function −
Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
Using the "correct" type doesn't make things better: Except for the virtual
functions all functions in the standard C++ library can have additional arguments as long as these are defaulted. Since the functions can also be declared with additional overloads (again with the exception of the virtual
function), you can end up trying to assign an overload set a variable. Thus, the code isn't portable and there is no way to make it portable by using some sort of cast or some signature instead of auto
.
The relevant quote is 17.6.5.5 [member.functions] paragraph 1:
An implementation may declare additional non-virtual member function signatures within a class:
--- by adding arguments with default values to a member function signature;
— by replacing a member function signature with default values by two or more member function signatures with equivalent behavior; and
— by adding a member function signature for a member function name.
I don't see a similar permission for non-member functions, though. Not sure where the permission to mess with these is hiding but I'm relatively sure that there are some weasel words for these as well. Looking further, it seems non-member functions are more constrained according to 17.6.5.4 [global.functions] paragraph 3:
An implementation shall not declare a global or non-member function signature with additional default arguments.
This would imply that you can take the address of the non-member functions, at least, when specifying the desired signature.
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