r - 检查 Rcpp 中 S4 对象的多重继承
问题描述
假设我在 R 中有以下两个类:
setClass("Person", representation(name = "character", age = "numeric"))
setClass("Employee", representation(boss = "Person"), contains = "Person")
我可以很容易地检查基础 R 中的继承:
employee <- new("Employee", name = "Jack", age = 25)
inherits(employee, "Employee")
#> [1] TRUE
inherits(employee, "Person")
#> [1] TRUE
我无法达到同样的效果Rcpp
:
Rcpp::cppFunction('
void check_class(Rcpp::S4 x) {
Rcout << "Class: " << as<std::string>(x.attr("class")) << std::endl;
Rcout << "x.inherits(\\"Employee\\") : " << x.inherits("Employee") << std::endl;
Rcout << "x.inherits(\\"Person\\") : " << x.inherits("Person") << std::endl;
Rcout << "Rf_inherits(x, \\"Employee\\") : " << Rf_inherits(x, "Employee") << std::endl;
Rcout << "Rf_inherits(x, \\"Person\\") : " << Rf_inherits(x, "Person") << std::endl;
Rcout << "R_extends : " << R_extends(x, Rf_mkString("Person"), R_GlobalEnv) << std::endl;
}')
check_class(employee)
#> Class: Employee
#> x.inherits("Employee") : 1
#> x.inherits("Person") : 0
#> Rf_inherits(x, "Employee") : 1
#> Rf_inherits(x, "Person") : 0
#> R_extends :
#> Error in extends(new("Employee", boss = new("Person", name = character(0), : 'class1' must be the name of a class or a class definition
我也希望x.inherits("Person")
如此true
。
如何检查对象是否继承自 Rcpp 中的父类?