On Thu, 4 Mar 2021 at 17:39, Subhomoy Ghosh <subhomo...@gmail.com> wrote:
>
> Hi,
>
>   This is related to my post. 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".

You can create a non-template parent class (e.g., Distribution) from
which your template class derives. Then you just return a pointer to
the parent. In [1] you'll see an example of this (Activity is the
parent class; Seize, Release and the others are template classes that
inherit from Activity). In your example, you can use something like

Rcpp::XPtr<Distribution> ptr(new Uniform2<double>(as<double>(max), D ), true);

[1] https://github.com/r-simmer/simmer/blob/master/src/activity.cpp

Iñaki

> // 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
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel@lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel



-- 
Iñaki Úcar
_______________________________________________
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to