jeudi 26 septembre 2019

Access Member Variables using templates

I need a template function that can serve generic purpose of accessing a member variable and operating functions present in that member variable. I have a set of functions to be called and this will solve my purpose.

I have tried the following

class Utilities {
public:
template<typename Container, typename MemberVar, typename Operator>
static void for_all(Container& C, MemberVar memvar, Operator Op) {
    for (auto& element : C) {
        (element.memvar->Op)();
    }
 }
};

I have the following test code where there is class Test that has PrivateImpl and DataStructure holding that privatimpl. Below is the print function that calls the Utilities::for_all function with privateimpl's print function

void Test::print() {
    ::Utilities::for_all(m_vec_struct_privateimpl,&Test::Struct_PrivateImpl::m_privateimpl,&Test::CPrivateImpl::print);
}

Below is the details about all the classes

// Main Class
class Test {
public:
    Test();
    ~Test();
    void print();
private:
    class CPrivateImpl;
    struct Struct_PrivateImpl;
    std::vector<Struct_PrivateImpl> m_vec_struct_privateimpl;
}; //class Utilities

// Class PrivateImpl
class Test::CPrivateImpl {
public:
    CPrivateImpl(std::initializer_list<int>& lst) {
        for (auto& i : lst) {
            m_vec_int.push_back(i);
        }

    }
    void print(int i) {
        cout << i << " ";
    }
private:
    std::vector<int> m_vec_int;

}; //class Test::CPrivateImpl

// Data Structure having PrivateImpl
struct Test::Struct_PrivateImpl {
public:

    Struct_PrivateImpl(int i) {
        m_privateimpl = std::make_shared<Test::CPrivateImpl>(std::initializer_list<int>{100+i,200+i,300+i});

    };
    ~Struct_PrivateImpl() {
    }

//private:
    std::shared_ptr<CPrivateImpl> m_privateimpl;
}; // class WiperSkeletonSomeIP::Struct_PrivateImpl

Test::Test(){
    for(auto i = 0u; i != 3; ++i) {
        Struct_PrivateImpl a_struct_pvtimpl(i);
        m_vec_struct_privateimpl.push_back(a_struct_pvtimpl);
    }
}
void Test::print() {
        ::Utilities::for_all(m_vec_struct_privateimpl,&Test::Struct_PrivateImpl::m_privateimpl,&Test::CPrivateImpl::print);
    }    

// This is the main function
int main() {
    Test t;
    t.print();
}

I am getting error message saying memvar has function Op.

This is an example code I have a lot of functions to be called within PrivateImpl class.

Please help me how to solve this.

Aucun commentaire:

Enregistrer un commentaire