无法调用函数引用 c++

Cant call function reference c++

本文关键字:引用 c++ 函数 调用      更新时间:2023-10-16

>我得到了这个需要函数引用的函数:

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 运算符来获取指向成员函数的指针。其次,你需要一个对象实例来调用函数,这有点像作为函数的第一个参数传递给函数。

有两种方法可以解决您的问题:

  1. 使用 lambda 表达式:

    make_timer([](){ DataHandler::dh().send(); }, 20);
    
  2. 使用std::bind

    make_timer(std::bind(&DataHandler::send, DataHandler::dh()), 20);