std :: function可以存储指向数据成员的指针吗? [英] Can a std::function store pointers to data members?
问题描述
从 cppreference ,我发现:
类模板std :: function是一个通用的多态函数包装器。 std :: function的实例可以存储,复制和调用任何Callable目标 - 函数,lambda表达式,绑定表达式或其他函数对象,以及指向成员函数的指针和指向数据成员的指针 。
我不明白为什么 std :: function
存储这样的指针,我从来没有听说过这个功能。
是真的可能,我错过了一些东西,或者是文档中的错误。
operator()
应如何处理这种情况?
从文档:
调用存储的可调用函数目标与参数args。
无论如何,没有存储的可调用函数目标在这里调用。我错了吗?
说实话,我甚至不知道什么是这样一个函数的正确语法,否则我会写一个例子来测试它。 br>
如何使用下面的模板定义一个指向数据成员的指针?
template<类R,类... Args>
class function< R(Args ...)>
调用函数调用操作符 std :: function< R(ArgTypes ...)>
:
R运算符()(ArgTypes ... args)const
11.2.4 [func.wrap.func.inv] / p1 ):
INVOKE(f,std :: forward< ArgTypes>(args)...,R)
其定义包括以下项目符号(§20.9.2 [func.require]/p1 ):
定义 INVOKE
(b,b,b)1.3 c> N <= 1 和<$
c $ c> f
是指向类T
和t1
的成员数据的指针。是类型T
的类型的对象或
对类型T
的对象的引用或对从T
;
派生类型的对象$ c> f 是指向存储在 std :: function
的内部调用器中的数据成员的指针,然后 std :: function
本身应该定义一个参数,例如:
std :: function< int(std :: pair< int,int>)> f =& std :: pair< int,int> :: first;
f(std :: make_pair(1,2));
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...)>
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(f, std::forward<ArgTypes>(args)..., R)
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));
这篇关于std :: function可以存储指向数据成员的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!