stricter arguments in Rcpp11/Rcpp14

January 16, 2015
By

(This article was first published on R Enthusiast and R/C++ hero, and kindly contributed to R-bloggers)

The way some classes (e.g. NumericVector have been implemented in various R/C++ versions gives us automatic coercion. For example passing an integer vector to a C++ function that has a NumericVector as an argument will coerce the integer vector into a numeric vector automatically.

// [[export]]
double foo( NumericVector x){  
   return sum(x) ;
}

will give us:

x <- c(1,2)  
foo(x)  
# 3

x <- c(1L, 2L)  
foo(x)  
# 3

Sometimes, we would like to restrict x to just be a numeric vector. For this we would typically have to use SEXP as the argument class and then test conformity manually, something like this:

// [[export]]
double foo( SEXP x_ ){  
   if( !is( x_ ) ) stop( "not a numeric vector" ) ;
   NumericVector x(x_) ;
   return sum(x) ;
}

Which is boring boiler plate code, so I’ve added the Strict class into Rcpp11 and Rcpp14. The class is pretty simple, it has two things:

  • a constructor taking a SEXP, which makes it a perfect candidate for an attributes generated function. The constructor stores the SEXP and checks if it is compatible using the appropriate is<> function, if not it throws an exception.
  • a get member function that returns a new object of the target class.

With this, we can write foo :

// [[export]]
double foo( Strict x){  
   return sum(x.get()) ;
}

To leave a comment for the author, please follow the link and comment on their blog: R Enthusiast and R/C++ hero.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)