Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created June 20, 2014 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/807ab47cdb730733caa9 to your computer and use it in GitHub Desktop.
Save romainfrancois/807ab47cdb730733caa9 to your computer and use it in GitHub Desktop.
abc
#include <Rcpp.h>
using namespace Rcpp ;
class abc {
public:
abc( SEXP x ) : data(x){}
inline operator SEXP() const {
return data ;
}
template <typename T>
class Proxy {
public:
Proxy( abc& ref_, int index_ ) : ref(ref_), index(index_){}
inline operator T() const {
return as<T>(ref.data[index]) ;
}
inline Proxy& operator=( const T& other ){
ref.data = Rf_shallow_duplicate(ref.data);
ref.data[index] = other ;
return *this ;
}
private:
abc& ref ;
int index ;
} ;
inline Proxy<NumericVector> a(){ return Proxy<NumericVector>(*this, 0); }
inline Proxy<IntegerVector> b(){ return Proxy<IntegerVector>(*this, 1); }
private:
List data ;
} ;
// [[Rcpp::export]]
abc test( abc obj ){
obj.a() = NumericVector::create(1,2,3) ;
obj.b() = seq(1, 5) ;
return obj ;
}
/*** R
obj <- structure( list( 1, 1L), class = "abc" )
x <- test( obj )
x
obj
*/
$ RcppScript /tmp/abc.cpp
> obj <- structure(list(1, 1), class = "abc")
> x <- test(obj)
> x
[[1]]
[1] 1 2 3
[[2]]
[1] 1 2 3 4 5
attr(,"class")
[1] "abc"
> obj
[[1]]
[1] 1
[[2]]
[1] 1
attr(,"class")
[1] "abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment