[Rcpp-devel] coercion NULL to vector

Serguei Sokol serguei.sokol at gmail.com
Tue Apr 17 15:09:30 CEST 2018


I would like to re-discuss the subject of automatic coercion of
NULL to some vector in function parameter list. This old topic was
already raised e.g. here

To resume, actually a function defined as (ivec is from RcppArmadillo package)

     // [[Rcpp::depends(RcppArmadillo)]]
     #include <RcppArmadillo.h>
     using namespace arma;
     // [[Rcpp::export]]
     ivec f(ivec x) {return x+1;}

and called as f(c()) will produce an error:
Error in f(c()) :
   Not compatible with requested type: [type=NULL; target=integer].

What I propose is (for this example) to mimic a call f(integer(0)) which gives:
 > f(integer(0))

The following one-line patch would do the job:
diff --git a/inst/include/Rcpp/r_cast.h b/inst/include/Rcpp/r_cast.h
index e59fa799..c0ec0817 100644
--- a/inst/include/Rcpp/r_cast.h
+++ b/inst/include/Rcpp/r_cast.h
@@ -63,6 +63,7 @@ namespace Rcpp {
              case LGLSXP:
              case CPLXSXP:
              case INTSXP:
+            case NILSXP:
                  return Rf_coerceVector(x, RTYPE);
                  const char* fmt = "Not compatible with requested type: "

It will automatically coerce NULL to a declared vector type.
It's a more primitive solution than Nullable<T> but in many cases
it can be largely sufficient and make code look shorter and clearer.

Will it break something in established usage habits? Is it compatible with your plans for Rcpp?
I can prepare a PR if you decide to include it.


More information about the Rcpp-devel mailing list