lundi 27 juin 2016

Pointer-to-member-function error


I am trying to use a pointer to a member function in my code so that I can easily replace the function to use without changing everywhere in the code. I get an error while compiling that I don't understand how to solve. Here is a minimum working example:

OrderBook.h

#include <list>
#include <string>

class Order
{

};

class OrderBook
{
    typedef void(OrderBook::* MatchingAlgorithm)(Order&, std::list<Order>&);
public:
    OrderBook(const std::string name);    
    void ExecuteFunction(Order&, std::list<Order>);
private:
    void FunctionToUse(Order&, std::list<Order>&);        
    const std::string m_OrderBookName;
    MatchingAlgorithm m_matchingAlgorithm;
};

OrderBook.cpp

#include "OrderBook.h"

OrderBook::OrderBook(
    const std::string name
    )
    : m_OrderBookName(name)
{
    m_matchingAlgorithm = &OrderBook::FunctionToUse;
}

void OrderBook::ExecuteFunction(Order & order, std::list<Order> listOfOrders)
{
    (*m_matchingAlgorithm)(order, listOfOrders);
}

void OrderBook::FunctionToUse(Order &, std::list<Order>&)
{
    // do nothing
}

Source.cpp

#include "OrderBook.h"

int main() 
{
    std::list<Order> mylist;
    Order o1, o2;    
    mylist.push_back(o1);
    mylist.push_back(o2);

    OrderBook ob("my book");

    ob.ExecuteFunction(o1, mylist);

    return 0;
}

Compilation Errors

error C2171: '*': illegal on operands of type 'OrderBook::MatchingAlgorithm'
error C2064: term does not evaluate to a function taking 2 arguments

If I replace (*m_matchingAlgorithm) with FunctionToUse inside ExecuteFunction the code compiles without errors.


Aucun commentaire:

Enregistrer un commentaire