What is the practical use of pointers to member functions?

后端 未结 12 1506
醉酒成梦
醉酒成梦 2020-12-03 08:13

I\'ve read through this article, and what I take from it is that when you want to call a pointer to a member function, you need an instance (either a pointer to one or a sta

12条回答
  •  温柔的废话
    2020-12-03 08:35

    Member pointers + templates = pure win.

    e.g. How to tell if class contains a certain member function in compile time

    or

    template
    TProperty grand_total(TContainer& items, TProperty (TElement::*property)() const)
    {
       TProperty accum = 0;
       for( auto it = items.begin(), end = items.end(); it != end; ++it) {
           accum += (it->*property)();
       }
       return accum;
    }
    
    auto ship_count = grand_total(invoice->lineItems, &LineItem::get_quantity);
    auto sub_total = grand_total(invoice->lineItems, &LineItem::get_extended_total);
    auto sales_tax = grand_total(invoice->lineItems, &LineItem::calculate_tax);
    

提交回复
热议问题