无法调用函数引用 c++
Cant call function reference c++
>我得到了这个需要函数引用的函数:
template <typename Fn>
void Caller::operator()(const Fn& funct, bool*is_running, int time_sec)
{
//Some code
funct();
}
我这样称呼它:
auto t = make_timer(DataHandler::dh().send, Data::sendPeriod);
发送函数在数据处理程序类中,我使用 dh 的静态实例:
static DataHandler& dh(){static DataHandler dh = DataHandler(); return dh;}
它返回错误:
error: must use '.*' or '->*' to call pointer-to-member function in 'funct (...)', e.g. '(...->* funct) (...)'
它说它从我称之为它的主场是必需的。
有人知道问题可能是什么吗?
最小、完整且可验证的示例:
#include <iostream>
#include "timer.h"
class DataHandler{
public:
static DataHandler& dh(){static DataHandler dh = DataHandler(); return dh;}
DataHandler(){};
void send(){std::cout << "send";}
};
int main()
{
auto t = make_timer(DataHandler::dh().send, 20);
return 0;
}
和计时器,虽然我不知道如何缩短它:(
#include <thread>
#include <functional>
struct Caller
{
template<typename Fn>
void operator()(const Fn& funct, bool*is_running, int time_sec);
};
template <typename Fn>
class Timer
{
protected:
std::thread timer_thread;
bool is_running;
public:
Timer(Fn fn, int time_sec);
Timer(const Timer&) = delete;
Timer(Timer&& timer);
void stop();
~Timer();
};
template <typename Fn>
void Caller::operator()(const Fn& funct, bool*is_running, int time_sec)
{
do
{
std::this_thread::sleep_for(std::chrono::milliseconds(time_sec*1000));
funct();
} while(*is_running);
}
template <typename Fn>
Timer<Fn>::Timer(Fn fn, int time_sec)
:
is_running(true)
{
Caller caller{};
auto proc = std::bind(caller, fn, &(this->is_running), time_sec);
std::thread tmp(proc);
swap(this->timer_thread, tmp);
}
template <typename Fn>
Timer<Fn>::Timer(Timer&& timer)
:
timer_thread(move(timer.timer_thread)),
is_running(timer.is_running)
{
}
template <typename Fn>
void Timer<Fn>::stop()
{
if(this->is_running)
this->is_running = false;
}
template <typename Fn>
Timer<Fn>::~Timer()
{
//this->stop();
timer_thread.join();
}
template<typename Fn>
Timer<Fn> make_timer(Fn fn, int time)
{
return Timer<Fn>{fn, time};
}
这不是将非静态成员函数作为回调传递的方法。
首先,您需要使用 address-of 运算符来获取指向成员函数的指针。其次,你需要一个对象实例来调用函数,这有点像作为函数的第一个参数传递给函数。
有两种方法可以解决您的问题:
-
使用 lambda 表达式:
make_timer([](){ DataHandler::dh().send(); }, 20);
-
使用
std::bind
:make_timer(std::bind(&DataHandler::send, DataHandler::dh()), 20);
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?