接收函子作为参数的最通用方法
Most general way to receive a functor as a parameter?
我正在为多线程方案编写一个包装器。它的操作应该类似于定时器。
我有一个特殊的类(clock
),它实现了一个叫做tick
的函数,这个函数应该传递给构造函数。如何将c++风格的函数(myClass::myfunction,与C的约定相反)描述为方法或构造函数的参数?
clock myInstance(otherClass::aMethod)
myInstance.tick(); // Should call otherClass::aMethod
myInstance.tick();
c++ 11和Bind有帮助吗?
可以调用类的静态成员函数,也可以调用对象的非静态成员函数。非静态成员函数需要有对象的上下文(this
指针)。
下面是一个简化的示例,说明如何使用函子和bind来调用成员函数。
#include <functional>
class clock
{
public:
clock(const std::function<void()>& tocall) : m_tocall(tocall) {}
void tick() {m_tocall();}
private:
std::function<void()> m_tocall;
};
class otherclass
{
public:
void aMethod() {}
};
int main(int argc, char *argv[])
{
otherclass A;
clock c( std::bind(&otherclass::aMethod, &A) );
c.tick(); // Will end up calling aMethod() of object A
}
您不需要为此使用std::function
。您需要有两个指针:一个是类对象,另一个指向该类的方法。简单地说,您需要使它能够做到:
CallNonVirtual(pClassPtr, pFuncAddr);
因此,你需要这两个参数,这样你就可以把叫做
(pClassPtr->*pFuncAddr)(); // Assuming no parameter
您可以这样做:
class Clock
{
COtherClass* pClassPtr;
/// Typedef simplifies
typedef void (COtherClass::*TargetFuncType)();
TargetFuncType pFuncAddr;
public:
Clock(COtherClass* pOther, TargetFuncType pFunc) :
pClassPtr(pOther), pFuncAddr(pFunc)
{
}
void tick()
{
(pClassPtr->*pFuncAddr)();
}
};
拨打电话:
int main()
{
COtherClass Obj;
Clock theClock(&Obj, &COtherClass::TheNonStatic);
theClock.tick();
}
相关文章:
- c++方法参数只能在linux的发布模式下自行更改
- 使用移动语义:右值引用作为方法参数
- 无法将动态创建的对象数组从 qml 发送到 c++ 作为方法参数
- 将方法参数类型更改为子类中的派生类
- ofstream作为C 中的方法参数
- 使用 gmock 匹配器将 std::function 设置为 EXPECT_CALL 中的方法参数
- C com 方法参数扣除
- 获取非静态方法参数计数
- 使用 gmock 返回模拟方法参数
- 运行 QML 时出现"未知方法参数类型"错误
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- 将C 方法参数转换为模板参数会因编译错误而失败
- 如何在方法参数中使用boost :: asio :: buffer
- qsharedPointer作为方法参数或方法的返回值的良好实践
- 如何将方法指针声明为Typedef方法参数
- 方法参数中的 OpenCV 垫"预期")""
- 方法参数中的 consst* 常量
- 带有“class”详细类型说明符的方法参数
- 具有原始方法参数派生类的 C++ 重载方法参数
- C++ std::string length() 或 size() 不适用于方法参数