【发布时间】:2019-06-25 10:26:34
【问题描述】:
我正在使用 Rcpp 为 C++ 库实现 R 包。该库从一个抽象类实现了几个派生类。函数初始化新的派生类并将其指针作为抽象类返回。是否可以在不更改 C++ 库的情况下使用 Rcpp 为 R 获得类似的构造?
这是一个简化的可重现示例:
#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);
}
compiled 代码的输出为:Derived
我当前的版本使用Rcpp::RCPP_MODULE 和Rcpp::XPtr。但是,这个版本不能像 C++ 实现那样使用:
#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)
;
}
执行示例:
(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...>
【问题讨论】:
-
你能添加R代码来完成这个最小的例子吗?
标签: c++ r inheritance abstract-class rcpp