同时处理非成员函数指针和成员函数指针
Handle non-member function pointer and member function pointer at the same time
我想做一个每X秒调用一次的成员函数。我做了一个小原型,可以处理非成员函数,但我不知道我做得好不好,我不能同时处理成员函数和非成员函数。
我有一个Event
对象,它使用基本计时器处理函数和延迟,以检测我们何时需要运行该函数:
typedef void (*ScheduleFunction)(float dt);
class Event
{
private:
ScheduleFunction m_Func;
double m_Timer;
double m_Delay;
public:
Event(ScheduleFunction function, double delay)
{
m_Func = function;
m_Delay = delay;
}
void Call(float dt)
{
m_Timer += dt;
if (m_Timer >= m_Delay)
{
m_Func(dt);
m_Timer = 0.0;
}
}
};
然后,我有另一个对象,它将每个帧的每个函数调用到一个vector<Event>
中:
class Handler
{
private:
void m_MemberFunction(float dt)
{
std::cout << "A member function." << std::endl;
}
std::vector<Event> m_ScheduleItems;
public:
Handler()
{
// This will not compile, because the function expect a non member function
Schedule(&Handler::m_MemberFunction, 1.0);
}
void CallScheduledFunctions(float dt)
{
for (std::vector<Event>::iterator it = m_ScheduleItems.begin(); it != m_ScheduleItems.end(); ++it)
{
it->Call(dt);
}
}
void Schedule(ScheduleFunction func, double delay)
{
Event event(func, delay);
m_ScheduleItems.push_back(event);
}
void Unschedule()
{
// TODO
}
};
如您所见,我有一个Schedule
注册新Event
的函数。但是现在,它只处理非成员函数。有没有办法处理非成员函数和成员函数,不仅从Handler
,而且在所有其他对象上
?如果没有办法,我怎么能做到这一点?
使用std::function
是要走的路。 任何可以调用的东西都可以转换/包装成std::function
。
在您的情况下,您可以像这样编写 Event 构造函数:
Event(std::function<void(float)>, double delay);
您可以使用独立函数、函子或 lambda 来调用它。 一些例子:
// declaration
auto myDummyFunction (float) -> void;
// Calling the constructor
auto event = Event(myDummyFunction,1.0);
如果我们想传递一个成员函数,只需使用 lambda:
// declaration of the class with the member function
class SomeOtherClass
{
public:
auto someMethod(float) -> void;
};
// Calling the constructor
auto someOtherClass = SomeOtherClass{};
auto event = Event([&someOtherClass](float f){someOtherClass.someMethod(v)},1.0);
总的来说,我发现lambda比std::binb方法更具可读性和灵活性。 据我所知,建议(是 Herb 还是 Scott?)不要再使用 std::bind 了,而是使用 lambda。
更新 1在下面添加了"调用任何对象的成员"。
短
我建议使用std::function
和std::bind
.但要提醒的是,由于内部机制,std::function 有一些开销!
std::function非常强大,因为你可以存储很多东西。
重要: 使用仅函数指针方法是可能的,但如果必须保留简单的统一接口,则会导致一些代码和复杂性。
例
#include <functional>
using ScheduleFunction_t = std::function<void(float)>;
class Event {
private:
ScheduleFunction_t
m_Func;
double
m_Timer,
m_Delay;
public:
Event(
ScheduleFunction_t const&function,
double delay)
: m_Func(function)
, m_Delay(delay)
{ }
void Call(float dt) {
m_Timer += dt;
if (m_Timer >= m_Delay)
{
// Important, if you do not assert in the constructor, check if the fn is valid...
// The ctr shouldn't throw on runtime assert fail... memory leak and incpomplete construction...
if(m_Func)
m_Func(dt);
m_Timer = 0.0;
}
}
};
如您所见,包括<functional>
标头将为您提供模板std::function<R(Args...)>
,其中 R 是返回类型,Args... 是完全限定参数类型的逗号分隔列表。
void g_freeFunction(float f) {
std::cout << "Globally floating for " << f << "ms" << std::endl;
}
class Handler {
private:
void m_MemberFunction(float dt) {
std::cout << "Floating around with " << dt << " m/s" << std::endl;
}
std::vector<Event> m_ScheduleItems;
public:
Handler() {
// Bind member function
Schedule<Handler, &Handler::m_MemberFunction>(this);
// Or free
Schedule(&g_freeFunction);
// Or lambda
Schedule([](float f) -> void { std::cout << "Weeeeeeeh...." << std::endl; });
}
void CallScheduledFunctions(float dt)
{
for(Event& e : m_ScheduleItems)
e.Call(dt);
}
template <typename TClass, void(TClass::*TFunc)(float)>
void Schedule(
TClass *const pInstance,
double delay = 0.0)
{
m_ScheduleItems.emplace_back(std::bind(TFunc, pInstance, std::placeholders::_1), delay); // Create in place at the end of vector.
}
void Schedule(
ScheduleFunction_t fn,
double delay = 0.0)
{
m_ScheduleItems.emplace_back(fn, delay); // Create in place at the end of vector.
}
void Unschedule() { /* TODO */ }
};
这样,您现在几乎可以绑定任何您想要的东西。 :D
更新:不能为具有匹配公共方法的任何其他类型调用 Schedule-函数,例如:
struct Test {
void foo(float f) {
std::cout << "TEST ME!" << std::endl;
}
};
int main()
{
Test t={};
Handler h = Handler();
h.Schedule<Test, &Test::foo>(&t);
for(uint32_t k=0; k < 32; ++k)
h.CallScheduledFunctions(k);
}
资源
http://en.cppreference.com/w/cpp/utility/functional http://en.cppreference.com/w/cpp/utility/functional/function http://en.cppreference.com/w/cpp/utility/functional/bind
工作示例
http://cpp.sh/7uluut
- 如果基类包含双指针成员,则派生类的构造函数
- C++正确的指针成员初始化
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- 为什么 operator() 处的指针成员不起作用?
- 更改队列指针成员的值需要在 C++ 中出现奇怪的错误
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- 结构对象的指针成员在传递给函数时被修改
- 参数的混合值,当我调用指针成员函数时
- 如何正确使用结构的共享指针成员?
- C++:私有类指针成员返回未定义的值
- 在函数中传递带有指针成员的结构是浅拷贝或深拷贝在 C 中
- 包含指针成员的嵌套结构
- 在 c++ 中,为什么 -> 被称为二进制中缀指针成员访问运算符?
- C++ 类指针成员行为奇怪(错误)
- 常量结构的指针成员
- 在类C++指针成员中
- 指针成员未在复制构造函数中初始化
- C++移动拥有指针成员的构造函数
- C++ 包含唯一指针成员变量的类的赋值运算符
- 如何使用 QPoint 指针成员对类进行排队和取消排队