简体   繁体   中英

How to use a class member function as defualt value

I have this class

class InventoryManagement
{
public:
    typedef void(InventoryManagement::*Action)(void);
    typedef void(InventoryManagement::*ActionWithReturn)(InventoryItem);

    void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = nullptr , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr);

    Action getStrategyOnMaxQtyReach();
    Action getStrategyOnQtyReset();
    Action getStrategyOnSideChange();
    ActionWithReturn getOnAdd();

private:

    // Private Functions Data members
    ActionWithReturn m_onAdd;
    Action m_OnSideChange;
    Action m_OnQtyReset;
    Action m_OnMaxQtyReach;


    // Default Function 
    void OnAddDefault(InventoryItem item) { }
    void OnMaxQtyReachDefault() { }
    void OnQtyResetDefault() { }
    void OnSideChangeDefault() { }
};

The function Initialize sets the data members of type Action . I created default actions that do noting and I want to pass them as default arguments. If the user doesn't send any function pointer to Initialize then those functions will be set.

The signature of the function is:

void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = nullptr , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr);

I tried void Initialize(int inventoryQty, int maxQty, ActionWithReturn onAdd = InventoryManagement::OnAddDefault , Action onMaxQtyReach = nullptr, Action onQtyReset = nullptr, Action onSideChnage = nullptr); instead of nullptr , but the compiler emitted "Call to non-static member function without an object argument" .

The syntax is &InventoryManagement::OnAddDefault :

void Initialize(
    int inventoryQty,
    int maxQty,
    ActionWithReturn onAdd = &InventoryManagement::OnAddDefault, // <-- 
    Action onMaxQtyReach = nullptr,
    //... etc
)

On a side node, I encourage you to consider using constructors instead of initialize methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM