如何通过RCPP在R中使用C++函数模板? [英] How can I use a C++ function template in R via Rcpp?
本文介绍了如何通过RCPP在R中使用C++函数模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用函数模板to_string
将int
转换为string
,在C++中没有问题,但如果我在R中执行,会出现以下错误:
main.cpp: In function 'std::string to_string(T)':
main.cpp:38:11: error: 't' was not declared in this scope
ss << t;
^
main.cpp: In function 'SEXPREC* sourceCpp_1_to_string(SEXP)':
main.cpp:134:36: error: 'T' was not declared in this scope
Rcpp::traits::input_parameter< T >::type tSEXP(tSEXPSEXP);
^
main.cpp:134:38: error: template argument 1 is invalid
Rcpp::traits::input_parameter< T >::type tSEXP(tSEXPSEXP);
^
main.cpp:134:46: error: expected initializer before 'tSEXP'
Rcpp::traits::input_parameter< T >::type tSEXP(tSEXPSEXP);
^
main.cpp:135:44: error: 'tSEXP' was not declared in this scope
rcpp_result_gen = Rcpp::wrap(to_string(tSEXP));
^
make: *** [main.o] Error 1
我搞不懂了,有别的办法吗?
//[[Rcpp::export]]
template <typename T>
std::string to_string(T t)
{
std::ostringstream ss;
ss << t;
return ss.str();
}
推荐答案
R根本不了解模板。事实上,R和C++之间的接口是CABI,因此所有C限制都适用。
因此,您不仅不能导出函数模板,而且也不能有意义地调用未导出的模板,因为您从R获得的类型是动态运行时类型,而不是静态类型。您需要执行运行时类型调度。
这篇关于如何通过RCPP在R中使用C++函数模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文