samedi 12 août 2023

Invalid use of non-static member function of a template class

I am getting below error when trying to assign callback function from a template class. I am accessing the callback function and the callback assignment function on the objects. I cannot make the callback function static, since it needs to access non-static pointer to Buffer object. How do I make this work?

Below is the code. This can be executed on https://www.onlinegdb.com/

main.cpp: In function ‘int main()’:
main.cpp:62:37: error: invalid use of non-static member function ‘void Class1::Callback() [with T = unsigned char]’
   62 |     pBuffer->SetWrCallback(pClass1->Callback);
      |                            ~~~~~~~~~^~~~~~~~
main.cpp:43:10: note: declared here
   43 |     void Callback()
      |          ^~~~~~~~
#include <iostream>

using namespace std;

using CallbackAfterWrite = void (*)(void);

template<typename T>
class Buffer
{
    public:
    Buffer() {}
    ~Buffer() {}
    
    std::size_t size()
    {
        return 10;
    }
    
    void SetWrCallback(CallbackAfterWrite wrCallback)
    {
        mWrCallback = wrCallback;
    }
    
    private:
    CallbackAfterWrite mWrCallback;
};

template<typename T>
class Class1
{
    public:
    Class1() {}
    ~Class1() {}
    
    void Callback()
    {
        if(0 != mpBuffer->size())
        {
            std::cout<< "Trigger callback" <<endl;
        }
    }
    
    private:
    Buffer<T> *mpBuffer;
};

int main()
{
    cout<<"Hello World"<<endl;
    
    Buffer<uint8_t>* pBuffer = new Buffer<uint8_t>;
    Class1<uint8_t>* pClass1 = new Class1<uint8_t>;
    
    pBuffer->SetWrCallback(pClass1->Callback);

    return 0;
}

This works if the callback function is static and does not need to access non-static private data members, but unfortunately, I cannot get away with it.

Aucun commentaire:

Enregistrer un commentaire