[Rcpp-devel] template functions with Rcpp

Kevin Ushey kevinushey at gmail.com
Sat May 2 07:40:00 CEST 2015


Hi Daniel,

Unfortunately, you cannot use // [[Rcpp::export]] to automagically export
template functions.

The general alternative approach is to define a template implementation,
and then dynamically dispatch to that implementation, e.g.

   template <typename T>
   void doStuffImpl() { ... }

with dispatch as

   // [[Rcpp::export]]
   void doStuff(SEXP object) {
       switch (TYPEOF(object)) {
       case INTSXP: return doStuffImpl<IntegerVector>();
       case REALSXP: return doStuffImpl<NumericVector>();
       ...
       }
   }

Of course, the way you implement your dispatch could differ, but generally
you need to manually map the opaque SEXP type to the appropriate Rcpp type
(or otherwise)

Hope this helps,
Kevin

On Friday, May 1, 2015, daniel castro <danielcastrob at gmail.com> wrote:
> Hello,
>
> I'm trying to build a function that calculates (for example) the log
> of all elements of a container. I want this container to be a vector,
> a Rcpp::numericVector , or perhaps a arama::colvec , so I'm trying
> with templates ,and it compiles without the // [[Rcpp::export]] part,
> but when I put it to export to R it doesn't work:
>
> //declaration
> template<class T>
> T Vlog(T vectorForm);
>
> //code
> // [[Rcpp::depends(RcppArmadillo)]]
> // [[Rcpp::export]]
> template<class T>
> T Vlog(T vectorForm)
> {
>
>
>    std::transform(vectorForm.begin(), vectorForm.end(),
> vectorForm.begin(), log);
>    return vectorForm;
> }
>
>
> gives 'T' was not declared in this scope.
>
> if possible, How could I fix it?
>
> Thank you in advance
> Daniel,
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150501/5119672d/attachment.html>


More information about the Rcpp-devel mailing list