[Rcpp-devel] smarter as<> template and Environment::operator[]

Romain Francois francoisromain at free.fr
Mon Jan 25 11:27:39 CET 2010


I've commited a smarter as<> template. The previous version was pretty 
stupid indeed, it was just throwing an exception so that only overloaded 
as were useful.

now as looks like this :

template <typename T> T as( SEXP m_sexp) {
	T t(m_sexp);
	return t ;

So basically anything that has a constructor taking a SEXP can be 
as<>'ed now.

This is now used in the Environment class, so that, is as<Foo> makes 
sense, which can come from :
- Foo has a constructor taking a SEXP
- someone have overloaded as<Foo>(SEXP)

then this makes sense :

Environment env = ... ; // some
Foo foo = env["x"] ;

Here is how it goes:
- env["x"] creates a Binding object
- Binding basically outsource implicit conversion to as

template <typename T> operator T() const{
	SEXP x = env.get(name) ;
     	T t = as<T>(x) ;
     	return t;

What happens when env["x"] is used on the lhs, is it smart as well. yep.

Bar bar ;
env["x"] = bar ;

in that second case Binding outsources transforming bar into a SEXP to 
wrap. so if there is an overloaded wrap(Bar), it works.

Don't you just love templates ?


Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
|- http://tr.im/KfKn : Rcpp 0.7.2
|- http://tr.im/JOlc : External pointers with Rcpp
`- http://tr.im/JFqa : R Journal, Volume 1/2, December 2009

More information about the Rcpp-devel mailing list