[Rcpp-devel] Deriving type information

Søren Højsgaard sorenh at math.aau.dk
Fri Feb 14 00:34:42 CET 2014

Dear all,

Function foo_num below takes a numeric vector and returns a list with the first element of the vector. (Not very interesting function). I want to create a templated version of this in function do_foo below, but whether "a" should be a double, an integer, or a string depends on the RTYPE. 

My question is (and it is embarrasing to ask because I believe Romain has already answered it; just can't find the answer) how to derive the what type "a" should have once we know RTYPE??

My second question is: Isn't there an easier general way to write the dispatch function (I have in mind situations where the templated function takes *more* than one argument!)? I have in mind something like:

  int type = TYPEOF(XX_) ;
  return do_foo<type> ( XX_ ) ;

but that fails because INTSXP, REALSXP etc seems to be defined as const's (thats my reading of the compiler message).


#include <Rcpp.h>
using namespace Rcpp;
List foo_num(NumericVector x){
  double a=x[0];
  return List::create( a );

template <int RTYPE>
List do_foo( Vector<RTYPE> x ){
  double a=x[0]; // WHAT TO DO HERE???
  return List::create( a );  

SEXP foo_any( SEXP& XX_){
  int type = TYPEOF(XX_) ;
  switch( type ){
  case INTSXP  : return do_foo<INTSXP> ( XX_ ) ;
  case REALSXP : return do_foo<REALSXP>( XX_ ) ;
  case STRSXP  : return do_foo<STRSXP> ( XX_ ) ;
  return R_NilValue ;

More information about the Rcpp-devel mailing list