Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call std::functions

I am trying to write a class template that would get two std::functions in the constructor parameter and call them upon construction and destruction, in a RAII style.

What am I missing?

template <class T>
class HelloGoodbye{
public:
HelloGoodbye(std::function<T> const & f, std::function<T> const &g)
  :mf(f),mg(g)
{
  mf();
}


~HelloGoodBye()
{
  mg();
}

private:
std::function<T> mf;
std::function<T> mg;
};


class Printer
{
    public:
    void hello()
    {
        std::cout << "hello!" << std::endl;
    }
    void goodbye()
    {
        std::cout << "Goodbye!" << std::endl;   
    }
};

int main()
{
      Printer p;
      auto hi = std::bind(&Printer::hello, &p);
      auto bye = std::bind(&Printer::goodbye, &p);
      HelloGoodbye hgb(hi,bye);      
}
like image 998
Llopeth Avatar asked Feb 28 '26 09:02

Llopeth


1 Answers

HelloGoodbye is a class template, you need to specify the template argument when use it. e.g.

HelloGoodbye<void()> hgb(hi,bye);   

LIVE

BTW: I suppose ~HelloGoodBye() is a typo of ~HelloGoodbye().

like image 109
songyuanyao Avatar answered Mar 04 '26 10:03

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!