0

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;
}
0811张庆昊
  • 538
  • 4
  • 16
  • Short answer: The purpose of `std::function` is to provide _type erasure_ for callable entities having the **same types of parameters and return values**. This is not your case. You can always use `std::any` for generic type erasure, but it's C++17. – Daniel Langr Dec 30 '20 at 12:50
  • @DanielLangr Amazing! It's so convenient. Thanks a lot! – 0811张庆昊 Dec 30 '20 at 13:00
  • For `C++17` `std::variant ` also can be used. [Sample](https://stackoverflow.com/a/65507709/13782669) – alex_noname Dec 30 '20 at 13:37

0 Answers0