From cppreference, I found that:
Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
I cannot see why a std::function
should be able to store such a pointer and I've never heard before about that feature.
Is it really possible, I missed something or that's an error in the documentation?
How should the operator()
behave in such a case?
As from the documentation:
Invokes the stored callable function target with the parameters args.
Anyway, there is no stored callable function target to invoke here. Am I wrong?
To be honest, I cannot even figure out what's the right syntax for such a function, otherwise I'd have written an example to test it.
How could the following template be used to define a pointer to data member?
template< class R, class... Args > class function<R(Args...)>
No. One is a function pointer; the other is an object that serves as a wrapper around a function pointer. They pretty much represent the same thing, but std::function is far more powerful, allowing you to do make bindings and whatnot.
std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them.
It lets you store function pointers, lambdas, or classes with operator() . It will do conversion of compatible types (so std::function<double(double)> will take int(int) callable things) but that is secondary to its primary purpose.
The effect of a call to the function call operator of std::function<R(ArgTypes...)>
:
R operator()(ArgTypes... args) const
is equivalent to (§ 20.9.11.2.4 [func.wrap.func.inv]/p1):
INVOKE<R>(f, std::forward<ArgTypes>(args)...)
whose definition includes the following bullet (§ 20.9.2 [func.require]/p1):
Define INVOKE(f, t1, t2, ..., tN) as follows:
[...]
1.3 —
t1.*f
whenN == 1
andf
is a pointer to member data of a classT
andt1
is an object of typeT
or a reference to an object of typeT
or a reference to an object of a type derived fromT
;
then, when f
is a pointer to a data member stored in an internal invoker of a std::function
, then the std::function
itself should define a single argument, e.g.:
std::function<int(std::pair<int,int>)> f = &std::pair<int,int>::first; f(std::make_pair(1, 2));
DEMO
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