0

I have tried code written on some link provided for dynamic function call , but unable to run code on machine .I tried to run code present at stackoverflow.com/questions/15764078/dynamically-creating-a-c-function-argument-list-at-runtime through member function. It is is giving bad call exception while running : Code snnippets

#include <iostream>
#include <functional>
#include <stdexcept>
#include <string>
#include <boost/any.hpp>

class Test;
class Test
{

public:
template <typename Ret, typename... Args>
Ret callfunc (std::function<Ret(Args...)>      func, std::vector<boost::any> anyargs);

template <typename Ret>
Ret callfunc (std::function<Ret()> func,    std::vector<boost::any> anyargs)
{
if (anyargs.size() > 0)
    throw std::runtime_error("oops, argument list too long");
return func();
}

template <typename Ret, typename Arg0, typename... Args>
Ret callfunc (std::function<Ret(Arg0, Args...)> func, std::vector<boost::any>anyargs){
    if (anyargs.size() == 0)
        throw std::runtime_error("oops, argument list too short");
        Arg0 arg0 = boost::any_cast<Arg0>(anyargs[0]);
        anyargs.erase(anyargs.begin());
        std::function<Ret(Args... args)> lambda =
    ([=](Args... args) -> Ret {
     return func(arg0, args...);
});
return callfunc (lambda, anyargs);
}

template <typename Ret, typename... Args>
std::function<boost::any(std::vector<boost::any>)> adaptfunc (Ret (Test::*func)(Args...)) {
std::function<Ret(Test*,Args...)> stdfunc = func;
   std::function<boost::any(std::vector<boost::any>)> result =
    ([=](std::vector<boost::any> anyargs) -> boost::any {
     return boost::any(callfunc(stdfunc, anyargs));
     });
return result;
}
int func1 (int a)
{
std::cout << "func1(" << a << ") = ";
return 33;
}

};

int main ()
{

Test a;
std::vector<std::function<boost::any(std::vector<boost::any>)>> fcs =
 {
    a.adaptfunc(&Test::func1)};

    std::vector<std::vector<boost::any>> args =
{{777}};

// correct calls will succeed
for (int i = 0; i < fcs.size(); ++i)
    std::cout << boost::any_cast<int>(fcs[i](args[i])) << std::endl;
return 0;
}

This code compiled successfully But it failed to run and crashed In main function for loop.

Community
  • 1
  • 1
SKM
  • 1
  • 1
  • 4

1 Answers1

0

Function needs typecast according to their signature e.g.:

a.adaptfunc((int(*)(int))&Test::func1)};

After this typecast function call will not fail

SKM
  • 1
  • 1
  • 4