首页 > 解决方案 > 不能调用函数参考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);

发送函数在 DataHandler 类中,我使用 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;
}

还有 timer.h 虽然我不知道如何缩短它:(

#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};
}

标签: c++functionreference

解决方案


这不是如何将非静态成员函数作为回调传递。

首先,您需要使用address-of 运算符来获取指向成员函数的指针。其次,您需要一个用于调用函数的对象实例,这有点像作为函数的第一个参数传递。

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

  1. 使用lambda 表达式

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

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

推荐阅读