mercredi 30 décembre 2020

How to put different template of std::function in a array? [duplicate]

Can I put different template of std::function in a array?

For example:

std::function<int(int)> funA;
std::function<int()> funB;
Sometype funArray[2] = {funA, FunB};

I tried to cast std::function<int(int)> to void*, it can be compiled successful, but the result was wrong, like this:

int a=0, b=0;
void* pFun = (void*)&funA;
std::function<int(int)> *fun = (std::function<int(int)> *)pFun;
(*fun)(a, b);

The method seems to work. But I must define the function at first. For example:

int Fun(int a)
{
    std::cout << a << std::endl;
    return ++(++a);
}

int main()
{
    std::function<int(int)> originPFun = Fun;
    void *ppFun;
    // ppFun = (void*)&Fun; // This way will cause segmentation fault
    ppFun = (void*)&originPFun; // This way can run seuccessful and get right result
    std::function<int(int)> *pFun = (std::function<int(int)>*)(ppFun);
    std::cout << (*pFun)(5) << std::endl;
    system("pause");
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire