简体   繁体   中英

Function pointer to a template class

I need some help on a strange mix between function pointers and templates...

My target :

You have a class : template<typename B> class A , and A instanciate a B member. Now I want to acces B getter/setter.

I tried this :

class B_example
{
public:
    B_example(int v):m_var(v){}
    int getVar() { return m_var; }
    void setVar(int v) { m_var = v; }

private:
    int m_var;
};


template<typename B> class A
{
public:
    A():m_b(B(5))
    {
        get = &m_b.getVar;
        set = &m_b.setVar;
    }

    int (B::*get)();
    void (B::*set)(int);

private:
    B m_b;
};


int main(int argc, char** argv)
{
    A<B_example> A_instance;
    B_example B_instance(5);


    int a = (A_instance.get*)();

    std::cout << a << std::endl;
}

Thank's for any help.

Alexandre

First, fix the syntax errors:

get = &B::getVar;
set = &B::setVar;

Then, the member-function pointer needs to be called on an object. Without knowing the purpose of these strange pointers, I can't guess what you want to do here. Maybe you want to call on B_instance :

int a = (B_instance.*A_instance.get)();

Or maybe you want to call it on the m_b object within A_instance ; but you can't do that because it's private. If that's the case, you probably just want regular member functions, rather than weird function pointers

int get() {return m_b.getVar();}
void set(int v) {m_b.setVar(v);}

These:

get = &m_b.getVar;
set = &m_b.setVar;

Should be:

get = &B::getVar;
set = &B::setVar;

And (A_instance.get*)() should be (B_instance.*A_instance.get)() .

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