Wednesday, July 16, 2014

Function overloading workaround in Rcpp


Rcpp does not support function overloading because R does not, but function overloading is such a useful feature that I have to find out some workaround, and here it is:

# c++ code

void addsome(int a, int b) {
 Rcout << "Sum of integers " << a << " and " << b << " is " << a+b << "\n";
}
void addsome(std::string a, std::string b) {
 Rcout << "Concatenate two strings: " << a+b << "\n";
}
// [[Rcpp::export]]
void addint(int a, int b) {
 addsome(a, b);
}
// [[Rcpp::export]]
void addstr(std::string a, std::string b) {
 addsome(a, b);
}

Note that very thin wrappers are used to export overloaded functions into R.

Then I tested them in R:

> sourceCpp("main.cpp")
> addint(2, 3);
Sum of integers 2 and 3 is 5
> addstr("Hello, ", "world!");
Concatenate two strings: Hello, world!

0 comments: