gpt4 book ai didi

c++ - Boost 的带有类成员函数的 Interpreter.hpp 示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:01 25 4
gpt4 key购买 nike

Boost 在

中带有示例文件

boost_1_41_0\libs\function_types\example

称为 interpreter.hppinterpreter_example.hpp

我试图创造一种情况,在这种情况下,我有一堆不同参数、返回类型等的函数,所有这些都注册并记录到一个位置。然后能够提取一个函数并使用一些参数执行它。

在阅读了这里的几个问题和其他一些来源后,我认为这个示例文件中实现的设计是我所能得到的最好的。它接受任何类型的函数,并允许您使用字符串参数列表调用它,该列表被解析为正确的数据类型。它基本上是一个控制台命令解释器,这可能就是它要说明的意思。

我一直在研究代码并四处寻找,试图获得相同的实现来接受类成员函数,但到目前为止一直没有成功。我想知道是否有人可以建议所需的修改,或者可能从事类似的工作并拥有一些相同的代码。

在这个例子中你会看到

interpreter.register_function("echo", & echo);
interpreter.register_function("add", & add);
interpreter.register_function("repeat", & repeat);

我想做类似的事情

test x;
interpreter.register_function("classFunc", boost::bind( &test::classFunc, &x ) );

但这破坏了任意数量的参数特性。所以我在想某种自动生成 boost::bind( &test::classFunc, &x, _1, _2, _3 ... ) 的方法,我只是不确定实现它的最佳方法。

谢谢

最佳答案

我一直在研究这个问题,我已经成功地让 boost 解释器接受成员函数,例如:

// Registers a function with the interpreter, 
// will not compile if it's a member function.
template<typename Function>
typename boost::enable_if< ft::is_nonmember_callable_builtin<Function> >::type
register_function(std::string const& name, Function f);

// Registers a member function with the interpreter.
// Will not compile if it's a non-member function.
template<typename Function, typename TheClass>
typename boost::enable_if< ft::is_member_function_pointer<Function> >::type
register_function(std::string const& name, Function f, TheClass* theclass);

enable_if语句用来防止在编译时使用错误的方法。现在,您需要了解的内容:

  • 它使用 boost::mpl 来解析可调用内置函数(基本上是一个函数指针)的参数参数类型
  • 然后,在编译时准备一个 fusion vector (可以同时存放不同类型的不同对象的 vector )
  • 当 mpl 完成对每个参数的解析后,“解析”应用方法将按照模板 fork “调用”应用方法。
  • 主要问题是内置可调用成员的第一个参数是包含被调用方法的对象。
  • 据我所知,除了可调用的内置函数(即 Boost::Bind 结果)之外,mpl 无法解析其他参数

因此,需要做的只是在“解析”应用程序中添加一个步骤,即将相关对象添加到应用程序循环中!开始了:

template<typename Function, typename ClassT>
typename boost::enable_if< ft::is_member_function_pointer<Function> >::type
interpreter::register_function( std::string const& name,
Function f,
ClassT* theclass);
{
typedef invoker<Function> invoker;
// instantiate and store the invoker by name
map_invokers[name]
= boost::bind(&invoker::template apply_object<fusion::nil,ClassT>
,f,theclass,_1,fusion::nil());
}

在解释器::调用器中

template<typename Args, typename TheClass>
static inline
void
apply_object( Function func,
TheClass* theclass,
parameters_parser & parser,
Args const & args)
{
typedef typename mpl::next<From>::type next_iter_type;
typedef interpreter::invoker<Function, next_iter_type, To> invoker;

invoker::apply( func, parser, fusion::push_back(args, theclass) );
}

这样,它将简单地跳过第一个参数类型并正确解析所有内容。该方法可以这样调用:invoker.register_function("SomeMethod",&TheClass::TheMethod,&my_object);

关于c++ - Boost 的带有类成员函数的 Interpreter.hpp 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1851315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com