I am implementing an R package for a C++ library using Rcpp. The library implements several derived classes from an abstract class. A function initializes new derived classes and returns a pointer of it as an abstract class. Is it possible to get a similar construct for R using Rcpp without changing the C++ library?
Here is a simplified reproducible example:
#include <iostream>
#include <string>
using namespace std;
// abstract class
class Base {
public:
virtual ~Base() {}
virtual std::string name() const = 0;
virtual Base* getNew() const = 0;
};
// derived class
class Derived: public Base {
public:
Derived() : Base() {}
virtual std::string name() const { return "Derived"; }
virtual Derived* getNew() const { return new Derived(); };
};
Base *newDerived( const std::string &name ) {
if ( name == "d1" ){
return new Derived ;
} else {
return 0 ;
}
};
int main( void ) {
Base* b = newDerived( "d1" ) ;
cout << b->name() << endl ;
return(1);
}
The output of the compiled code is: Derived
My current version uses Rcpp::RCPP_MODULE
and Rcpp::XPtr
. However, this version is not usable like the C++ implementaion:
#include <Rcpp.h>
using namespace Rcpp;
//... Base and Derived class and newDerived function implementations ... //
// wrapper function for pointer
typedef Base* (*newDerivedPtr)(const std::string& name);
//[[Rcpp::export]]
Rcpp::XPtr< newDerivedPtr > getNewDerived(const std::string type) {
return(Rcpp::XPtr< newDerivedPtr >(new newDerivedPtr(&newDerived)));
}
RCPP_MODULE(mod) {
Rcpp::class_< Base >("Base")
;
Rcpp::class_< Derived >("Derived")
.derives<Base>("Base")
.default_constructor()
.method("name", &Derived::name)
;
}
An example execution:
(dv = new(Derived))
# C++ object <0x101c0ce20> of class 'Derived' <0x101b51e00>
dv$name()
# [1] "Derived"
(dvptr = getNewDerived("d1"))
# pointer: 0x101c82770> // WANTED: C++ Object <0x...> of class 'Base' <0x...>