将其与lambda函数结合以捕获局部变量。
前段时间,Borland在他们的BCB环境中引入了对c++语言的扩展。这个扩展是一个__closure关键字。问题是,是否有可能在普通c++或c++ 11中实现这些功能?如果你不熟悉__closure关键字,下面的代码在注释中提供了解释。
提前感谢!Toreno
#include <stdio.h>
// __closure keyword is used here !
typedef void (__closure * MemberCallback)(int x, int y, int z);
class A
{
private:
MemberCallback callback;
public:
A() : callback(NULL)
{
}
void setCallback(MemberCallback newCallback)
{
callback = newCallback;
}
void call(int x, int y, int z)
{
if(callback)
callback(x, y, z);
else
printf("NOT SET(%i, %i, %i)n", x, y, z);
}
};
class B
{
public:
void func1(int x, int y, int z)
{
printf("FUNC 1(%i, %i, %i)n", x, y, z);
}
void func2(int x, int y, int z)
{
printf("FUNC 2(%i, %i, %i)n", x, y, z);
}
};
int main()
{
// A and B classes do not know about each other. There is no possibility
// to for inheritance because B class can implement multiple instances
// of callback function
A a;
B b;
a.call(1, 2, 3); // Prints: NOT SET(1, 2, 3)
a.setCallback(b.func1);
a.call(4, 5, 6); // Prints: FUNC 1(4, 5, 6)
a.setCallback(b.func2);
a.call(7, 8, 9); // Prints: FUNC 2(7, 8, 9)
return 0;
}
std::函数正是您正在寻找的。如果您想了解如何在库中实际实现这样的机制,这里有一系列关于它的博客文章。
用完整的代码重新散列前面的答案,对于像我一样想要快速参考通用模式的其他人:
#include <functional>
#include <stdio.h>
// __closure replacement
typedef std::function<void(int x, int y, int z)> MemberCallback;
class A
{
public:
void setCallback( MemberCallback newCallback ) {
callback_ = newCallback;
}
void call( int x, int y, int z ) {
if ( callback_ )
callback_( x, y, z );
else
printf( "NOT SET(%i, %i, %i)n", x, y, z );
}
private:
MemberCallback callback_;
};
class B
{
public:
void func1( int x, int y, int z ) {
printf( "FUNC 1(%i, %i, %i)n", x, y, z );
}
void func2( int x, int y, int z ) {
printf( "FUNC 2(%i, %i, %i)n", x, y, z );
}
};
int main( )
{
// A and B classes do not know about each other. There is no possibility
// to for inheritance because B class can implement multiple instances
// of callback function
A a;
B b;
a.call( 1, 2, 3 ); // Prints: NOT SET(1, 2, 3)
a.setCallback( [&b](int x, int y, int z){ b.func1(x, y, z); } );
a.call( 4, 5, 6 ); // Prints: FUNC 1(4, 5, 6)
a.setCallback( [&b](int x, int y, int z){ b.func2(x, y, z); } );
a.call( 7, 8, 9 ); // Prints: FUNC 2(7, 8, 9)
return 0;
}
输出:NOT SET(1, 2, 3)
FUNC 1(4, 5, 6)
FUNC 2(7, 8, 9)