gpt4 book ai didi

c++ - 为什么传递非静态成员函数会导致编译错误?

转载 作者:行者123 更新时间:2023-11-30 04:56:20 25 4
gpt4 key购买 nike

当我尝试调用下面的构造函数并向其传递一个静态成员函数时,我没有得到任何错误,但是当我向它传递一个非静态成员函数时,我得到一个编译错误:

构造函数

template <class callable, class... arguments>
Timer(int after, duration_type duration, bool async, callable&& f, arguments&&... args)
{

std::function<typename std::result_of<callable(arguments...)>::type()>
task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

}

调用

Timer timer(252222, duration_type::milliseconds, true, &MotionAnalyser::ObjectGarbageCollector); // Does not work because it does not point to object too.

Timer timer(252222, duration_type::milliseconds, true, std::bind(this, &MotionAnalyser::ObjectGarbageCollector)); //Should work, but does not?!?!

错误

Error   C2039   'type': is not a member of 'std::result_of<callable (void)>'    

到目前为止我有:

  • 研究了如何使用 std:function,结果是在结合可调用类型,调用对象应该是可调用类型,因为我覆盖了 () 运算符(基于我的了解可调用类型)。
  • 我研究过将非静态成员函数传递给函数因此我尝试使用 std::bind
  • 在 Google 上搜索有关编译错误的有用信息。

最佳答案

您向后调用 bind,它首先获取可调用对象(在本例中为指向成员函数的指针),然后是参数。

std::bind(&MotionAnalyser::ObjectGarbageCollector, this)

但是,查看 Timer 的构造函数,您应该能够传递这些参数,因为它们无论如何都会被绑定(bind):

Timer timer(252222, duration_type::milliseconds, true,
&MotionAnalyser::ObjectGarbageCollector, this);

关于c++ - 为什么传递非静态成员函数会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com