[Rcpp-devel] Exposing constructors

Romain Francois romain at r-enthusiasts.com
Thu Nov 4 11:29:43 CET 2010


Hello,

This question has come up a few times now. How can I use another 
constructor than the default constructor in a class exposed by Rcpp 
modules.

I've made a few changes to Rcpp to allow that. The new restriction is 
that :
- we can only expose one constructor (we need to think about various 
ways to implement dispatch)
- the constructor needs to have 0, 1 or 2 arguments. We will handle more 
later, but I wanted people to test this first before launching a massive 
copy/paste adventure. Also, the pattern is simple enough so that other 
people can do it instead of me. (I can explain it a bit more if people 
volunteer).

As an illustration, consider this simple class :

class Randomizer {
public:
	Randomizer( double min_, double max_) : min(min), max(max_){}

	NumericVector get( int n ){
		RNGScope scope ;
		return runif( n, min, max );
	}

private:
	double min, max ;
} ;

I can explain what it does, but I feel this is self explanatory.

What is relevant here is the constructor. There is no default 
constructor (although the compiler might generate one on our behalf), 
and we want to use the constructor that takes two doubles.

This is how we would do it (the syntax might change before Rcpp 0.8.9 is 
out):

RCPP_MODULE(mod){

	class_< Randomizer, init_2<double,double> >( "Randomizer" )
		.method( "get" , &Randomizer::get ) ;

}

The relevant bit here is the second template argument of class_.

Full example below:


require( Rcpp )
require( inline )
inc <- '

class Randomizer {
public:
	Randomizer( double min_, double max_) : min(min), max(max_){}

	NumericVector get( int n ){
		RNGScope scope ;
		return runif( n, min, max );
	}

private:
	double min, max ;
} ;

RCPP_MODULE(mod){

	class_< Randomizer, init_2<double,double> >( "Randomizer" )

		.method( "get" , &Randomizer::get ) ;

}
'

fx <- cxxfunction( , '', includes = inc, plugin = "Rcpp" )
mod <- Module( "mod", getDynLib( fx ) )
Randomizer <- mod$Randomizer
r <- new( Randomizer, 10.0, 20.0 ) ;
r$get(10)
r$get(5)


Have fun !

Romain


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/czHPM7 : Rcpp Google tech talk on youtube
|- http://bit.ly/9P0eF9 : Google slides
`- http://bit.ly/cVPjPe : Chicago R Meetup slides




More information about the Rcpp-devel mailing list