无法调用函数引用c ++

时间:2018-05-18 07:39:37

标签: c++ function reference

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

  1. 使用lambda expression

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

    make_timer(std::bind(&DataHandler::send, DataHandler::dh()), 20);
    
相关问题