Daniel
Daniel

Reputation: 5

How to call a class method whose object is inside a function

How to call a class method GetItemList that takes as input a method of another class (B, C or D) whose object exists in the class Pro

I try call

GetItemList<void, B>(&B::Show_B);

I get

class B' has no member named 'func'

How to prevent it from creating a new object when calling std :: function

Objects for list

class A
{
};

class B : public A
{
public:
    void Show_B()
    {
        std::cout << "Class B" << std::endl;
    };
};

class C : public A
{
public:
    void Show_C()
    {
        std::cout << "Class C" << std::endl;
    };
};

class D : public A
{
public:
    void Show_D()
    {
        std::cout << "Class D" << std::endl;
    }
};

typedef std::vector<A*> List;

Class which call template

class Pro
{
private:
    List* m_list;

public:
    Pro(List* list)
    {
        m_list = list;

        // GetItemList<void, B>(&B::Show_B);
        // GetItemList<void, C>(&C::Show_C);
        // GetItemList<void, D>(&D::Show_D);
    }

    template <typename V, typename T> void GetItemList(std::function<V(T*)> func)
    {
        T* pointer = nullptr;
        for(auto& p : *m_list) {
            pointer = dynamic_cast<T*>(p);
            if(pointer != nullptr)
                pointer->func();
        }
    }
};

Main function

void Main()
{
    List list;
    list.push_back(new B);
    list.push_back(new C);
    list.push_back(new D);

    Pro pro(&list);
}

Upvotes: 0

Views: 69

Answers (1)

Jarod42
Jarod42

Reputation: 217810

It should be

template <typename V, typename T> void GetItemList(std::function<V(T*)> func)
{
    T* pointer = nullptr;
    for (auto& p : *m_list) {
        pointer = dynamic_cast<T*>(p);
        if(pointer != nullptr)
            func(pointer);
    }
}

Demo

Upvotes: 2

Related Questions