0

I am trying to write an Rcpp function fun1 that can call another Rcpp function generically (let's say fun2). One possibility I could think about is to use an input argument that is a string containing the name of the function fun2.

 NumericVector fun1(NumericVector x, std::string name_of_fun2) { 
         
         NumericVector y = fun2(x);
         return(y);
}

I do not know how to fill in the missing code as I'm new to C++. One thing that I tried and that works is to use switch case statements, but the problem is that I need to define a big list of all possible functions fun2 that could be called in advance.

MiP
  • 1
  • 1
    There are several ways to attack this. Using a `switch` is one valid option, but it may be better to study `C++` a little more as there are ample standard `C++` approaches to this problem (e.g. virtual functions). – Joseph Wood Apr 28 '21 at 01:38
  • Functions could be passed as arguments using pointers or even using the standard library functional. Since your functions will be different each time, you must have a generic idea of what they are then create a template. I presume you are going down to the basics of R. I have never been in a position to do this – Onyambu Apr 28 '21 at 01:56
  • 2
    There is also this question https://stackoverflow.com/q/14428687/4408538 which was turned into an excellent `Rcpp` gallery post https://gallery.rcpp.org/articles/passing-cpp-function-pointers/. – Joseph Wood Apr 28 '21 at 02:15
  • @JosephWood Thanks for your helpful answer. The gallery post has also an if else statement (if (fstr == "fun1") ) similar to the switch case solution I mentioned. I was wondering if there is a way to access the function without such such a statement. – MiP Apr 29 '21 at 03:34

0 Answers0