[Rcpp-devel] Passing template class as argument in Rcpp function

Subhomoy Ghosh subhomoy25 at gmail.com
Thu Mar 4 17:38:41 CET 2021


Hi,

  This is related to my post
<https://stackoverflow.com/questions/66142449/passing-class-as-argument-in-rcpp-function?noredirect=1#comment116942069_66142449>.
My question is in the same spirit except for one additional complexity. How
can one create a new instance of a *template* class object with a pointer
on it and create an external pointer that can be further passed as an
argument of a function? Here is a small example of my goal that will
obviously not run and show "Use of class template Uniform2 requires
template arguments".

// template class
template <typename T>
class Uniform2 {

public:
  Uniform2(T max_,mat D_) :
  max(max_), D(D_) {}

  ~Uniform2(){};

  T max;
  mat D;
};


/// get function
// [[Rcpp::export]]
XPtr<Uniform2> getUniform(const mat &D, SEXP max,char type) {
  // create pointer to a template Uniform object and
  // wrap it as an external pointer
  if(type=='double') {
          Rcpp::XPtr<Uniform2> ptr(new Uniform2<double>(as<double>(max), D
), true);
          return ptr;
  } else if(type=='int') {
          Rcpp::XPtr<Uniform2> ptr(new Uniform2<int>(as<int>(max), D ),
true);
          return ptr;
   }
  // return the external pointer to the R side
  return Rcpp::XPtr<Uniform2>(R_NilValue);
}



//do something
// [[Rcpp::export]]
double test2(double z, XPtr<Uniform2> xp) {

  double CC= z * xp->max;

  return CC;

}

Thanks,
Subhomoy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20210304/1b10d3c7/attachment.html>


More information about the Rcpp-devel mailing list