Skip to content

Instantly share code, notes, and snippets.

@gogonzo
Last active January 6, 2020 10:13
Show Gist options
  • Save gogonzo/f1360c4e1c13143c261afcecfa34ca01 to your computer and use it in GitHub Desktop.
Save gogonzo/f1360c4e1c13143c261afcecfa34ca01 to your computer and use it in GitHub Desktop.
Calling another cpp function in templated Rcpp function
#include <Rcpp.h>
#include <string>
#include <vector>
// [[Rcpp::plugins("cpp11")]]
std::string nth_string(Rcpp::NumericVector& x, int i) {
return std::to_string(x[i]);
}
double nth_numeric(Rcpp::NumericVector& x, int i) {
return x[i];
}
template <typename T>
using RcppVec = Rcpp::Vector<Rcpp::traits::r_sexptype_traits<T>::rtype>;
template <int ITYPE, typename FTYPE>
auto apply_cpp_fun(Rcpp::Vector<ITYPE> const& x, FTYPE fun) ->
RcppVec<typename std::result_of<FTYPE>::type> {
int n = x.size();
RcppVec<typename std::result_of<FTYPE>::type> res(n);
for (int i = 0; i < n; i++) {
res[i] = fun(x, i);
}
return res;
}
// [[Rcpp::export]]
Rcpp::NumericVector test1_cpp(Rcpp::NumericVector x) {
return apply_cpp_fun(x, nth_numeric);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment