Ale*_*lex 9 c++ stdbind c++11 std-function
我正在玩std :: function和std :: bind,我注意到一些不直观的东西,我想更好地理解它.
例如:
void fun()
{
}
void hun(std::string)
{
}
int main()
{
function<void(int)> g = &fun; //This fails as it should in my understanding.
function<void(int)> f = std::bind(fun); //This works for reasons unknown to me
function<void(int, std::string)> h = std::bind(hun); //this doesn't work
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何function<void(int)>将一个函数绑定到void().然后我可以调用f(1)并获得乐趣().我想了解这是如何完成的.进入微软Visual Studio 2012的实现,让我迷失在无法理解的宏观之中.所以这就是我在这里问这个问题的原因.
如果不使用参数占位符(_1,, _2...),那么传递给返回的函数对象的任何参数std::bind都将被丢弃.附:
std::function<void(int)> f = std::bind(fun, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)
我得到了一个(长而丑陋的)错误.
对于对Standardese感兴趣的人:
§20.8.9.1.2 [func.bind.bind]
template<class F, class... BoundArgs>
*unspecified* bind(F&& f, BoundArgs&&... bound_args);
Run Code Online (Sandbox Code Playgroud)
p3返回:
g具有弱结果类型(20.8.2)的转发调用包装器.当cv表示cv -qualifiers时, should 的效果g(u1, u2, ..., uM)应该是INVOKE(fd, v1, v2, ..., vN, result_of<FD cv (V1, V2, ..., VN)>::type),并且绑定参数的值和类型的确定如下所述.gv1, v2, ..., vNp10绑定参数的值
v1, v2, ..., vN及其对应的类型V1, V2, ..., VN取决于TiD从调用派生的类型bind和调用包装器的cv -qualifiers cv,g如下所示:
- 如果
TiD是reference_wrapper<T>,则参数为tid.get()且其类型Vi为T&;- 如果值为
is_bind_expression<TiD>::valueistrue,则参数为tid(std::forward<Uj>(uj)...)且其类型Vi为result_of<TiD cv (Uj...)>::type;- 如果该值
j的is_placeholder<TiD>::value不为零时,所述参数是std::forward<Uj>(uj)与它的类型Vi是Uj&&;- 否则,值为
tid,其类型Vi为TiD cv &.
通过调用函数模板生成的转发调用包装器bind可以接受任意数量的额外参数; 这些都会被忽略.bind表达式的有效arity和最小签名placeholder由其构造中使用的s以及它们绑定的可调用参数确定.