Does using callbacks in C++ increase coupling?

前端 未结 8 1743
予麋鹿
予麋鹿 2021-01-03 11:04

Q1. Why are callback functions used?

Q2. Are callbacks evil? Fun for those who know, for others a nightmare.

Q3. Any alternative to

8条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 11:39

    Q3. Any alternative to callback?

    I prefer the functor form of callback. e.g. this sort of thing:

    class WidgetContainerOrProcessorOfSomeSort
    {
    public:
      struct IWidgetFunctor
      {
        virtual bool operator()( const Widget& thisWidget )=0;
      };
      ....
      bool ProcessWidgets( IWidgetFunctor& callback )
      {
         .....
         bool continueIteration = callback( widget[ idxWidget ] );
         if ( !continueIteration ) return false;
         .....
      }
    };
    
    struct ShowWidgets : public WidgetContainerOrProcessorOfSomeSort::IWidgetFunctor
    {
      virtual bool operator(){ const Widget& thisWidget }
      {
         thisWidget.print();
         return true;
      }
    };
    
    WidgetContainterOrProcessorOfSomeSort wc;
    wc.ProcessWidgets( ShowWidgets() );
    

    It always seems a bit verbose for simple samples, but in the real world I find it much easier than trying to remember exactly how to construct complex function pointer declarations :-)

提交回复
热议问题