How can Rcpp::wrap
and Rcpp::as
methods be written for classes that contain an Rcpp
class?
For example, the following .cpp
file compiles using sourceCpp()
:
#include <Rcpp.h>
namespace Rcpp {
class myVector {
public:
NumericVector data;
myVector(NumericVector v) : data(v) {};
};
template <> myVector as(SEXP v) {
return myVector(v);
}
template <> SEXP wrap(const myVector& v) {
return v.data;
}
}
//[[Rcpp::export]]
Rcpp::myVector test(Rcpp::myVector& x){
return x;
}
In this example, we create a vector that is comprised simply of a single Rcpp class (NumericVector
) and an Rcpp::as
and Rcpp::wrap
method so that it can be used as an argument in any exported function.
However, the code does not pass when creating an Rcpp package as follows:
- Rstudio -> New Project -> New Directory -> R package using Rcpp
- Copy above script into new file,
test.cpp
- Build -> Install and Restart
There are no complaints about the test.cpp
but there are complaints in src/RcppExports.cpp
. Here's the relevant function:
// test
Rcpp::myVector test(Rcpp::myVector& x);
RcppExport SEXP _test_test(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::myVector& >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(test(x));
return rcpp_result_gen;
END_RCPP
}
The errors are:
Line 19: `myVector` does not name a type;
Line 24: `myVector` was not declared in this scope
... template argument 1 invalid, qualified-id in declaration, 'x' not declared, 'test' not declared... side-effects of above two errors.
I do know how to write Rcpp::as
and Rcpp::wrap
for classes that do NOT contain Rcpp classes (templated case, general case):
#include <RcppCommon.h>
- Forward-declaration of class, may depend on C++ libraries (not
Rcpp.h
) #include <Rcpp.h>
Unfortunately, Rcpp::myVec
requires Rcpp.h
and thus cannot be declared prior to including Rcpp.h
.
Can external classes containing Rcpp classes make use of Rcpp::wrap
and Rcpp::as
? If so, is there any precedent I can view for details? I haven't found any despite quite a bit of searching, or maybe I'm overlooking something very simple.