动态函数通过映射和参数通过模板解压缩成员函数

时间:2015-09-18 03:24:16

标签: function templates boost dynamic

我已尝试在为动态函数调用提供的某些链接上编写的代码,但无法在机器上运行代码。我试图通过成员函数运行stackoverflow.com/questions/15764078/dynamically-creating-a-c-function-argument-list-at-runtime处的代码。  它在运行时给出了错误的调用异常: 代码片段

#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;
}

此代码已成功编译 但它无法运行和崩溃 在循环的主要功能。

1 个答案:

答案 0 :(得分:0)

函数需要根据其签名进行类型转换,例如:

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

此类型转换后,函数调用不会失败