Cliff AB
Cliff AB

Reputation: 1190

C++ Class with Rcpp::Function member

Using Rcpp, I would like to be able to create a C++ class that has a Rcpp::Function for a field. For example:

class myClass{
    Rcpp::Function myR_fun;
    myClass(Rcpp::Function userR_fun){
        myR_fun = userR_fun;
    }
};

Unfortunately, the above code does not work. When compiling, the following error is reported:

error: constructor for 'myClass' must explicitly initialize the member 'myR_fun'
which does not have a default constructor
    myClass(Rcpp::Function userR_fun){
    ^

The error report is a bit confusing, because I think I have initialized myR_fun in the constructor for myClass?

A workaround I could use is to have a void pointer

class myClass{
    void* vFunPtr;
    myClass(Rcpp::Function userR_fun){
        vFunPtr = &userR_fun;
    }
};

but this seems suboptimal from an organizational perspective. What is the proper way to make an Rcpp::Function object to be a field of a C++ class?

Upvotes: 3

Views: 245

Answers (1)

rustyx
rustyx

Reputation: 85266

With your syntax, myR_fun is first default-constructed, then assigned userR_fun.

Try this instead:

class myClass {
    Rcpp::Function myR_fun;
    myClass(Rcpp::Function userR_fun)
        : myR_fun(userR_fun)
    {}
};

With this syntax myR_fun is directly constructed using userR_fun.

Upvotes: 5

Related Questions