Default NULL parameter Rcpp

前端 未结 1 873
借酒劲吻你
借酒劲吻你 2021-01-04 09:29

I am trying to define a function with a default NULL parameter in Rcpp. Following is an example:

// [[Rcpp::export]]
int test(int a         


        
相关标签:
1条回答
  • 2021-01-04 10:06

    You are in luck. We needed this in mvabund and Rblpapi, and have it since the last (two) Rcpp releases.

    So try this:

    // [[Rcpp::export]]
    int test(int a, Rcpp::Nullable<Rcpp::IntegerVector> kfolds = R_NilValue) {
    
      if (kfolds.isNotNull()) {
         // ... your code here but note inverted test ...
    

    A nice complete example is here in Rblpapi. You can also set a default value as you did (subject to the usual rules in C++ of all options to the right of this one also having defaults).

    Edit: For completeness sake, here is a full example:

    #include <Rcpp.h>
    
    // [[Rcpp::export]]
    int testfun(Rcpp::Nullable<Rcpp::IntegerVector> kfolds = R_NilValue) {
    
      if (kfolds.isNotNull()) {
        Rcpp::IntegerVector x(kfolds);
        Rcpp::Rcout << "Not NULL\n";
        Rcpp::Rcout << x << std::endl;
      } else {
        Rcpp::Rcout << "Is NULL\n";
      }
      return(42);
    }
    
    /*** R
    testfun(NULL)
    testfun(c(1L, 3L, 5L))
    */
    

    which generates this output:

    R> sourceCpp("/tmp/nick.cpp")

    R> testfun(NULL)
    Is NULL
    [1] 42
    
    R> testfun(c(1L, 3L, 5L))
    Not NULL
    1 3 5
    [1] 42
    R> 
    
    0 讨论(0)
提交回复
热议问题