Search code examples
c++rrcppellipsis

Rcpp - Define a C++ function that takes an R function and an ellipsis argument


I have an R function bar that takes another R function foo, defined as follows:

foo <- function(x,y) x + y
bar <- function(foo, z, ...) z + foo(...)

A call to bar would be of the form:

bar(foo, 1,2,3)

Now with foo defined as above, I want to create a C++ version of bar. Here's what I've tried:

library(Rcpp)
cppFunction(
'
  double bar(Function foo, double z, ...) {
  return z + foo(...);
 }
 ')

This clearly doesn't work. What would be the right way to define this function in C++?

Thanks.


Solution

  • It might be easier to turn your ellipsis into a list before feeding it to Rcpp

    bar <- function(foo, z, ...) {
       args <- list(...)
       bar_internal(foo, z, args)
    }
    

    And then your Rcpp function can simply take a Rcpp::List instead of ellipsis.

    double bar_internal(Function foo, double z, List args){
    
    }