在Bjarne Stroustrup的主页(C++ 11 FAQ)中:
struct X { int foo(int); };
std::function<int(X*, int)> f;
f = &X::foo; //pointer to member
X x;
int v = f(&x, 5); //call X::foo() for x with 5
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?std :: function如何调用foo成员函数?
模板参数int(X*, int),是&X::foo从转换成员函数指针到一个非成员函数指针?!
(int(*)(X*, int))&X::foo //casting (int(X::*)(int) to (int(*)(X*, int))
Run Code Online (Sandbox Code Playgroud)
澄清:我知道我们不需要使用任何指针来使用std :: function,但我不知道std :: function的内部如何处理成员函数指针和非成员函数之间的这种不兼容性指针.我不知道标准如何允许我们实现像std :: function这样的东西!
任何人都可以解释一下int ((*foo(int)))(int)这是什么吗?
int (*fooptr)(int);
int ((*foo(int)))(int); // Can't understand what this does.
int main()
{
fooptr = foo(0);
fooptr(10);
}
Run Code Online (Sandbox Code Playgroud)
.
我最近在读代码,发现函数指针写成:
int (*fn_pointer ( this_args ))( this_args )
Run Code Online (Sandbox Code Playgroud)
我经常会遇到这样的函数指针:
return_type (*fn_pointer ) (arguments);
Run Code Online (Sandbox Code Playgroud)
这里讨论类似的事情:
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我有什么区别,这是如何工作的?
关于教程promgrammingWithObjectiveC.
在处理返回块或将其他块作为参数的块时,自定义类型定义特别有用.请考虑以下示例:
void (^(^complexBlock)(void (^)(void)))(void) = ^ (void (^aBlock)(void)) {
...
return ^{
...
};
};
Run Code Online (Sandbox Code Playgroud)
complexBlock变量引用一个块,该块将另一个块作为参数(aBlock)并返回另一个块.
重写代码以使用类型定义使这更具可读性:
typedef void (^XYZSimpleBlock)(void);
XYZSimpleBlock (^betterBlock)(XYZSimpleBlock) = ^ (XYZSimpleBlock aBlock) {
...
return ^{
...
};
};
Run Code Online (Sandbox Code Playgroud)
我的重写代码:
但我无法理解源代码:
void (^(^complexBlock)(void (^)(void)))(void) = ^ (void (^aBlock)(void)) {
...
return ^{
...
};
}
Run Code Online (Sandbox Code Playgroud)
据我所知,它应该是:
(void (^) (void)) (^complexBlock) (void (^)(void) = ^ (void (^aBlock)(void)) {
...
return ^{
...
};
};
Run Code Online (Sandbox Code Playgroud)