如何使用默认参数导出 Rcpp 类方法 [英] How to export Rcpp Class method with default arguments

查看:41
本文介绍了如何使用默认参数导出 Rcpp 类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 c++ 类 myClass,它有一个方法 foo(int x=0) 并且它有一个参数 x,默认值为 0.c++ 类可以通过

I have a c++ class myClass which has a method foo(int x=0) and it has a parameter x with default value = 0. The c++ class could be exported to R by

RCPP_MODULE(my_module) {
    class_< myClass >( "myClass" )
    .constructor()
    .method( "foo", &myClass::foo )
    ;
}

但是,在 R 中,我无法在不指定 x 的值的情况下调用 myClass$foo.无论默认值如何,我都必须指定 x 的值.

However, in R, I am not able to call myClass$foo without specifying the value of x. I have to specify the value of x regardless the default value.

所以我的问题是如何使用默认参数导出 Rcpp 类方法.我试图通过互联网搜索它.我发现的最接近的是

So my question is how to export Rcpp class method with default arguments. I tried to search it over the internet. The closest thing that I found was

using namespace Rcpp;
double norm( double x, double y ) { return sqrt( x*x + y*y );
}
RCPP_MODULE(mod_formals2) {
    function("norm", &norm,
}

但它在我的情况下不起作用.

But it doesn't work in my case.

推荐答案

我最近遇到了同样的问题.查看rcpp处理类的源文件后(~/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include/Rcpp/module/class.h 在我的设置中)我认为目前不可能.

I had the same problem recently. After looking at the source file of rcpp handling the classes (~/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include/Rcpp/module/class.h in my setup) I don't think that it is currently possible.

我想出的最佳解决方法是在 R 中创建一个包装器来处理默认参数.

The best workaround I came up with was to create a wrapper in R to handle the default arguments.

这是一个完整的示例,演示了如何执行此操作.我定义了一个简单的函数,它接受 3 个参数并输出它们的总和.第二个和第三个参数是可选的,默认设置为 10100.

Here is a full example demonstrating how to do it. I defined a simple function that accepts 3 arguments and outputs their sum. The second and third arguments are optional and set by default to 10 and 100.

#include <Rcpp.h>

class  MWE {
public:
  int sum_them(int mandatory_arg,
               int optional_arg1,
               int optional_arg2)
  {
    return (mandatory_arg+optional_arg1+optional_arg2);
  }
};

RCPP_MODULE(mod_mwe) {
  Rcpp::class_<MWE>( "MWE" )
  .constructor()
  .method("sum_them", &MWE::sum_them)
  ;
}

mwe.R

require('Rcpp')

# source the C++ code
sourceCpp('mwe.cpp')

# create an instance of the class:
my_mwe = new(MWE)

# assign a wrapper with default arguments to the instance:
assign('sum_them_wrapper',
       function(mandatory_arg,
                optional_arg1=10,
                optional_arg2=100) {
         return(my_mwe$sum_them(mandatory_arg, optional_arg1, optional_arg2))
       },
       envir = my_mwe
       )

这会输出预期的结果:

> my_mwe$sum_them_wrapper(3, optional_arg2=500)
[1] 513

这篇关于如何使用默认参数导出 Rcpp 类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆